using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using Infragistics.WebUI.UltraWebChart;
using Infragistics.WebUI.UltraWebGauge;
using Infragistics.WebUI.UltraWebGrid;
using Infragistics.UltraChart.Resources.Appearance;
using Infragistics.UltraChart.Resources.Effects;
using Infragistics.UltraChart.Shared.Styles;
using Infragistics.UltraChart.Data.Series;
using Infragistics.UltraChart.Core.Primitives;
using AjaxControlToolkit;
using MBLocale;

/// <summary>
/// Summary description for Dashboards
/// </summary>
public class Dashboards
{
    bool bWidgetPage = false;
    DataTable dtWidgetProperty = null; // Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
    int dashboardColumns = 2;
    ArrayList SeriesBindingCharts = new ArrayList();
	public Dashboards()
	{
        //Report r = new Report();
        //ISection sec = r.AddSection();
        //this.UltraWebGridDocumentExporter1.Export(this.UltraWebGrid1, sec);
        //this.UltraChart1.RenderPdfFriendlyGraphics(sec.AddCanvas().CreateGraphics());
        SeriesBindCharts();
	}

    /// <summary>
    /// This function will return the Query used to Generate the Widget
    /// </summary>
    /// <param name="strDBafrowid">af_row_id of WidgetRecord</param>
    /// <returns></returns>
    private string GetWidgetSQL(string strDBafrowid)
    {
        HDDatabase HDD = new HDDatabase();
        string result = "";
        try
        {
            string sql = "select * from sy_widgets where af_row_id = '" + strDBafrowid + "'";
            DataRow dr = HDD.GetTableRow(sql);
            result = GetWidgetSQL(dr);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetWidgetSQL :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }



    /// <summary>
    /// This will get the Widget's data in ref DataTable and Query in the ref string
    /// </summary>
    /// <param name="dr">DataRow of the Widget Record</param>
    /// <param name="strWidgetSQL">ref string to get the Widget Query</param>
    /// <param name="dtWidgetData">ref dataTable to get the Widget Data</param>
    private void GetWidgetData(DataRow dr,ref string strWidgetSQL,ref DataTable dtWidgetData,HtmlForm frmObj,ref ArrayList arrXAxis,ref ArrayList arrYAxis)
    {
            HDDatabase HDD = new HDDatabase();
            try
            {
                if (dr != null)
                {
                    string strSourceType = dr["source_type"].ToString();
                    string strSource = dr["source"].ToString();
                    string sql = "";
                    DataTable dt = new DataTable();
                    DataSet dsPageControls = new DataSet();
                    DataTable dtWidgetOrdinates = GetWidgetOrdinates(dr["af_row_id"].ToString());

                    switch (strSourceType.ToLower())
                    {
                        case "query":
                            sql = "select * from sy_report_sql where af_row_id = '" + dr["source"].ToString() + "'";
                            dt = HDD.GetDataTable(sql);
                            //decode added by Sampath on 27-Apr-2012
                            //CommonFunctions.decodeData(dt);
                            if (dt != null)
                                if (dt.Rows.Count > 0)
                                {
                                    strWidgetSQL = dt.Rows[0]["report_base_sql"].ToString();

                                    Hashtable htParam = new Hashtable();
                                    BuildParameters BP = new BuildParameters();
                                    htParam = BP.updateParameters(strWidgetSQL, dt.Rows[0]["report_base_param"].ToString(), frmObj, dr["af_row_id"].ToString());
                                    //GetParametersInHashTable(ref htParam, strWidgetSQL, dt.Rows[0]);
                                    //GetPageControls(htParam, ref dsPageControls);
                                    //GetValuesofParameters(dr["af_row_id"].ToString(), ref htParam, frmObj,dsPageControls);
                                    
                                    //if(htParam.Count>0)
                                    //    foreach (string str in htParam.Keys)
                                    //    {
                                    //        if (strWidgetSQL.Contains(str))
                                    //            strWidgetSQL = strWidgetSQL.Replace(str, htParam[str].ToString());
                                    //    }

                                    strWidgetSQL = BP.makeSQL(htParam, strWidgetSQL);
                                    dtWidgetData = HDD.GetDataTable(strWidgetSQL);

                                    GetXYOrdinatesInArray(ref arrXAxis, ref arrYAxis, dtWidgetOrdinates, true, dtWidgetData);

                                }
                            break;
                        case "report":
                            sql = "select * from sy_report where af_row_id = '" + dr["source"].ToString() + "'";
                            dt = HDD.GetDataTable(sql);
                            if (dt != null)
                                if (dt.Rows.Count > 0)
                                {
                                    DataRow drReport = dt.Rows[0];
                                    #region QueryBasedReport
                                    if (drReport["rpt_base_object"].ToString().ToLower() == "true" || drReport["rpt_base_object"].ToString().ToLower() == "sql")
                                    {
                                        string strReportAtt = "select * from sy_report_att where rpt_id = '" + dr["source"].ToString() + "' order by attrib_sequence";
                                        DataTable dtReportAtt = HDD.GetDataTable(strReportAtt);
                                        if (dtReportAtt != null)
                                            if (dtReportAtt.Rows.Count > 0)
                                            {
                                                string strObjectID = dtReportAtt.Rows[0]["object_id"].ToString();
                                                if (strObjectID.Trim() != "")
                                                {
                                                    string strsql = "select * from sy_report_sql where report_base_id = '" + strObjectID + "'";
                                                    DataTable dtSQL = HDD.GetDataTable(strsql);
                                                    //decode added by Sampath on 27-Apr-2012
                                                    //CommonFunctions.decodeData(dtSQL);
                                                    if (dtSQL != null)
                                                        if (dtSQL.Rows.Count > 0)
                                                        {
                                                            strWidgetSQL = dtSQL.Rows[0]["report_base_sql"].ToString();



                                                            Hashtable hsParam = new Hashtable();
                                                            //GetParametersInHashTable(ref hsParam, strWidgetSQL, dtSQL.Rows[0]);
                                                            //GetPageControls(hsParam, ref dsPageControls);
                                                            //GetValuesofParameters(dr["af_row_id"].ToString(), ref hsParam, frmObj,dsPageControls);
                                                            //if (hsParam.Count > 0)
                                                            //    foreach (string str in hsParam.Keys)
                                                            //    {
                                                            //        if (strWidgetSQL.Contains(str))
                                                            //            strWidgetSQL = strWidgetSQL.Replace(str, hsParam[str].ToString());
                                                            //    }
                                                            BuildParameters BP = new BuildParameters();
                                                            hsParam = BP.updateParameters(strWidgetSQL, dtSQL.Rows[0]["report_base_param"].ToString(), frmObj, dr["af_row_id"].ToString());
                                                            strWidgetSQL = BP.makeSQL(hsParam, strWidgetSQL);


                                                            dtWidgetData = HDD.GetDataTable(strWidgetSQL);
                                                            Hashtable htcaptions = new Hashtable();
                                                            HashColumnNames(ref htcaptions, dtReportAtt);
                                                            ReplaceColumnCaptions(htcaptions, ref dtWidgetData);
                                                            RemoveColumns(htcaptions, ref dtWidgetData);
                                                            GetXYOrdinatesInArray(ref arrXAxis, ref arrYAxis, dtWidgetOrdinates,false, dtWidgetData);
                                                        }
                                                }
                                            }


                                    }
                                    #endregion
                                    #region ObjectBasedReport
                                    else if (drReport["rpt_base_object"].ToString().ToLower() == "false" || drReport["rpt_base_object"].ToString().ToLower() == "object")
                                    {
                                        
                                            sql = "select * from sy_report_att where rpt_id = '"+drReport["af_row_id"].ToString()+"' order by attrib_sequence";
                                            DataTable dtReportAtt = HDD.GetDataTable(sql);
                                            if (dtReportAtt != null)
                                            {
                                                if (dtReportAtt.Rows.Count > 0)
                                                {
                                                    string object_id = dtReportAtt.Rows[0]["object_id"].ToString();
                                                    string tablename = HDD.GetColumnValue("select object_table from sy_obj where object_id = '" + object_id + "'");

                                                    DataTable dtPgCtr = HDD.GetDataTable("select * from sy_pg_ctr where page_id = (select af_row_id from sy_pg where object_id = '"+object_id+"')");
                                                    DataTable dtBind = GetBindFields(dtPgCtr);

                                                    if (drReport["rpt_base_object"].ToString().ToLower() == "false") // Old Maxblox Report
                                                    {
                                                        string strQuery = "select ";
                                                        string strAttribID = "";
                                                        foreach (DataRow dr1 in dtReportAtt.Rows)
                                                        {
                                                            strAttribID += "'"+dr1["attrib_id"].ToString()+"',";
                                                            DataRow drbnd = null;
                                                            DataRow[] drctr = dtPgCtr.Select("control_attrib_id= '" + dr1["attrib_id"].ToString() + "'");
                                                            if (drctr.Length > 0)
                                                            {
                                                                if (drctr[0]["control_bind_id"].ToString().Trim() != "")
                                                                {
                                                                    drbnd = dtBind.Select("af_row_id='" + drctr[0]["control_bind_id"].ToString() + "'")[0];
                                                                }
                                                            }

                                                            if (drbnd != null)
                                                            {
                                                                string innersql = "(select top 1 " + drbnd["bind_text"].ToString() + " from " + drbnd["bind_table"].ToString() + " where " + drbnd["bind_value"].ToString() + "= [" + tablename + "].[" + dr1["attrib_id"].ToString() + "])";
                                                                strQuery += innersql + " as [" + dr1["caption"].ToString() + "],";
                                                            }
                                                            else
                                                            {
                                                                strQuery += dr1["attrib_id"].ToString() + " as [" + dr1["caption"].ToString() + "],";
                                                            }
                                                        }

                                                        strQuery = strQuery.TrimEnd(',');
                                                        strAttribID = strAttribID.TrimEnd(',');
                                                        strQuery += " from " + tablename + " where 1=1 ";

                                                        
                                                        strWidgetSQL = strQuery;
                                                        bool status = dr["ignore_owner_security"].ToString() != "" ? Convert.ToBoolean(dr["ignore_owner_security"].ToString()) : false;
                                                        if (!status)
                                                        {
                                                            SecurityFilter SF = new SecurityFilter();
                                                            strWidgetSQL = SF.applysecurity(strWidgetSQL);
                                                        }
                                                        else
                                                        {
                                                           strWidgetSQL = applyafadminsecurity(strWidgetSQL);
                                                        }

                                                        dtWidgetData = HDD.GetDataTable(strWidgetSQL);

                                                        GetXYOrdinatesInArray(ref arrXAxis, ref arrYAxis, dtWidgetOrdinates, false, dtWidgetData);
                                                        
                                                    }
                                                    else if (drReport["rpt_base_object"].ToString().ToLower() == "object") // New Maxblox Report
                                                    {
                                                        string strObjAtt = "select * From sy_obj_att where object_id = (select af_row_id from sy_obj where object_id = '"+object_id+"')";
                                                        DataTable dtObjAtt = HDD.GetDataTable(strObjAtt);
                                                        string strQuery = "select ";

                                                        foreach (DataRow dratt in dtReportAtt.Rows)
                                                        {

                                                            string strattibID = "";
                                                            string caption = "";
                                                            DataRow[] drObj = dtObjAtt.Select("af_row_id = '" + dratt["attrib_id"].ToString() + "'");
                                                            if (drObj.Length > 0)
                                                                strattibID = drObj[0]["attrib_id"].ToString();

                                                            if(dratt["caption"].ToString()!="")
                                                                caption = dratt["caption"].ToString();
                                                            else
                                                            {
                                                                caption = strattibID;
                                                                if(drObj.Length>0)
                                                                    caption = drObj[0]["attrib_name"].ToString();
                                                            }


                                                            DataRow drbnd = null;
                                                            DataRow[] drctr = dtPgCtr.Select("control_attrib_id= '" + strattibID + "'");
                                                            if (drctr.Length > 0)
                                                            {
                                                                if (drctr[0]["control_bind_id"].ToString().Trim() != "")
                                                                {
                                                                    drbnd = dtBind.Select("af_row_id='" + drctr[0]["control_bind_id"].ToString() + "'")[0];
                                                                }
                                                            }

                                                            if (drbnd != null)
                                                            {
                                                                string innersql = "(select top 1 " + drbnd["bind_text"].ToString() + " from " + drbnd["bind_table"].ToString() + " where " + drbnd["bind_value"].ToString() + "= [" + tablename + "].[" + strattibID + "])";
                                                                strQuery += innersql + " as [" + caption + "],";
                                                            }
                                                            else
                                                            {
                                                                strQuery += strattibID + " as [" + caption + "],";
                                                            }

                                                        }

                                                        strQuery = strQuery.TrimEnd(',');
                                                        strQuery += " from " + tablename + getWhereCondForObj(tablename, drReport, dtPgCtr, HDD); //" where 1=1"); // Modified by Imran Gani on 04-Dec-12, for Source Filter.
                                                        strWidgetSQL = strQuery;
                                                        bool status = dr["ignore_owner_security"].ToString() != "" ? Convert.ToBoolean(dr["ignore_owner_security"].ToString()) : false;
                                                        if (!status)
                                                        {
                                                            SecurityFilter SF = new SecurityFilter();
                                                            strWidgetSQL = SF.applysecurity(strWidgetSQL);
                                                        }
                                                        else
                                                        {
                                                           strWidgetSQL = applyafadminsecurity(strWidgetSQL);
                                                        }
                                                        dtWidgetData = HDD.GetDataTable(strWidgetSQL);
                                                        
                                                        GetXYOrdinatesInArray(ref arrXAxis, ref arrYAxis, dtWidgetOrdinates, false, dtWidgetData);

                                                        MBFunctions MBF = new MBFunctions(); // Added by 'Imran Gani' on 03-Feb-2014, for currency conversion. 
                                                        MBF.HandleCurrencyColumn(dtWidgetData, object_id);
                                                    }
                                                }
                                            }
                                    }
                                    #endregion
                                }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error : GetWidgetSQL : " + ex.Message);
            }
            finally
            {
                HDD = null;
            }
        

    }
   
    /// <summary>
    /// This will return the Query used to get the Widget.
    /// </summary>
    /// <param name="dr">DataRow of the Widget</param>
    /// <returns></returns>
    private string GetWidgetSQL(DataRow dr)
    {
        string result = "";
        HDDatabase HDD = new HDDatabase();
        DataTable dt = new DataTable();
        try
        {
            ArrayList arrXAxis = new ArrayList();
            ArrayList arrYAxis = new ArrayList();
            GetWidgetData(dr, ref result, ref dt, null, ref arrXAxis, ref arrYAxis);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetWidgetSQL : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }

    /// <summary>
    /// This will create Widget in the referenced HTMLTableCell with source from DataTable
    /// </summary>
    /// <param name="dt">DataSource of the Widget</param>
    /// <param name="type">Chart Type</param>
    /// <param name="drWidget">DataRow of Widget</param>
    /// <param name="htc">ref HtmlTableCell on which the Widget will be rendered</param>
    /// <param name="is3D">Whether to display the Widget in 2D/ 3D mode</param>
    /// Added by 'Imran Gani' on 10-Oct-2012, to create chart from MS-chart control.
    private void RenderWidgetFromMSChart(DataTable dt, string type, DataRow drWidget, ref HtmlTableCell htc, bool is3D, HtmlForm frmObj)
    {
        HDDatabase HDD = new HDDatabase();
        Chart objChart = null;
        Series objSeries = new Series();
        bool isTextChart = false;
        System.Web.UI.DataVisualization.Charting.ChartArea objChartArea = new System.Web.UI.DataVisualization.Charting.ChartArea();
        UltraWebGrid Grid = null;
        try
        {
            if (type.Trim() != "")
            {
                switch (type.Trim().ToLower())
                {
                    case "area2d":
                    case "area3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Area;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Rotation = 25;
                            objChartArea.Area3DStyle.Inclination = 30;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                            objChartArea.Area3DStyle.LightStyle = LightStyle.Realistic;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "bar2d":
                    case "bar3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Bar;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Rotation = 20;
                            objChartArea.Area3DStyle.Inclination = 30;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "column2d":
                    case "column3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Column;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Rotation = 30;
                            objChartArea.Area3DStyle.Inclination = 30;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "doughnut2d":
                    case "doughnut3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Doughnut;
                        if (is3D)
                        {
                            switch (drWidget["label_display"].ToString().ToLower()) // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                            {
                                case "none":
                                    objSeries["PieLabelStyle"] = "Disabled";
                                    break;
                                case "outside":
                                    objSeries["PieLabelStyle"] = "Outside";
                                    break;
                                default:
                                    objSeries["PieLabelStyle"] = "Inside";
                                    break;
                            }
                            objSeries["DoughnutRadius"] = "50";
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                            objChartArea.Area3DStyle.Inclination = 45;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "funnel2d":
                    case "funnel3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Funnel;
                        if (is3D)
                        {
                            objSeries["FunnelStyle"] = "YIsHeight";
                            objSeries["FunnelLabelStyle"] = "Outside";
                            objSeries["FunnelOutsideLabelPlacement"] = "Right";
                            objSeries["FunnelPointGap"] = "0";
                            objSeries["FunnelMinPointHeight"] = "1";
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "line2d":
                    case "line3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Line;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Rotation = 20;
                            objChartArea.Area3DStyle.Inclination = 0;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "pyramid2d":
                    case "pyramid3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Pyramid;
                        if (is3D)
                        {
                            objSeries["PyramidLabelStyle"] = "Outside";
                            objSeries["PyramidOutsideLabelPlacement"] = "Right";
                            objSeries["PyramidPointGap"] = "0";
                            objSeries["PyramidMinPointHeight"] = "1";
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "spline2d":
                    case "spline3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Spline;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Rotation = 30;
                            objChartArea.Area3DStyle.Inclination = 10;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "stepline2d":
                    case "stepline3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.StepLine;
                        if (is3D)
                        {
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Rotation = 30;
                            objChartArea.Area3DStyle.Inclination = 20;
                            objChartArea.Area3DStyle.WallWidth = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "pie2d":
                    case "pie3d":
                        objChart = new Chart();
                        objSeries.ChartType = SeriesChartType.Pie;
                        if (is3D)
                        {
                            switch (drWidget["label_display"].ToString().ToLower()) // Added by 'Imran Gani' on 13-Aug-2014, for Dashboard widget property
                            {
                                case "none":
                                    objSeries["PieLabelStyle"] = "Disabled";
                                    break;
                                case "outside":
                                    objSeries["PieLabelStyle"] = "Outside";
                                    break;
                                default:
                                    objSeries["PieLabelStyle"] = "Inside";
                                    break;
                            }
                            objChartArea.Area3DStyle.Perspective = 0;
                            objChartArea.Area3DStyle.Enable3D = true;
                            objChartArea.Area3DStyle.Inclination = 45;
                        }
                        objChart.ChartAreas.Add(objChartArea);
                        objChart.Series.Add(objSeries);
                        break;
                    case "table":
                        Grid = new UltraWebGrid();
                        break;
                    case "text":
                        isTextChart = true;
                        break;
                    default:
                        break;
                }
                if (objChart != null)
                {
                    ApplyMSChartSettings(objChart, drWidget);
                    CreateTable(drWidget, ref htc, objChart, frmObj);
                }
                else if (Grid != null)
                {
                    ApplyGridSettingsNew(ref Grid, drWidget);
                    htc.BorderColor = "LightGray";
                    CreateTable(drWidget, ref htc, Grid, frmObj);
                }
                else if (isTextChart) // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Text widget
                    createTextContent(drWidget, ref htc, frmObj);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RenderWidget :" + ex.Message);
        }
        finally
        {
            dt = null;
            HDD = null;
            objChart = null;
        }
    }

    /// <summary>
    /// This will create Widget in the referenced HTMLTableCell with source from DataTable
    /// </summary>
    /// <param name="dt">DataSource of the Widget</param>
    /// <param name="type">Chart Type</param>
    /// <param name="drWidget">DataRow of Widget</param>
    /// <param name="htc">ref HtmlTableCell on which the Widget will be rendered</param>
    /// <param name="is3D">Whether to display the Widget in 2D/ 3D mode</param>
    private void RenderWidget(DataTable dt, string type, DataRow drWidget, ref HtmlTableCell htc, bool is3D,HtmlForm frmObj)
    {
        //DataTable dt = new DataTable();
        HDDatabase HDD = new HDDatabase();
        UltraChart chart = null;
        UltraWebGrid Grid = null;
        try
        {
            if (type.Trim() != "")
            {
                switch (type.Trim().ToLower())
                {
                    case "area":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.AreaChart3D;
                            //chart.Data.SwapRowsAndColumns = true;
                            chart.Transform3D.Perspective = 0;
                            chart.Data.ZeroAligned = true;
                            //chart.ColorModel.Skin.ApplyRowWise = true;
                            

                            chart.Transform3D.XRotation = 130;
                            chart.Transform3D.YRotation = 15;
                            chart.Transform3D.ZRotation = 0;
                            //chart.Axis.X.NumericAxisType = NumericAxisType.
                        }
                        else
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.AreaChart;
                        break;
                    case "bar":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.BarChart3D;
                            //chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Stack3DBarChart;
                            //chart.Data.SwapRowsAndColumns = true;
                            //chart.ColorModel.Skin.ApplyRowWise = false;
                            chart.Data.ZeroAligned = true;
                            chart.Transform3D.Perspective = 0;

                            chart.Transform3D.XRotation = 130; //220
                            chart.Transform3D.YRotation = 20; //25
                            chart.Transform3D.ZRotation = 0;
                            
                        }
                        else
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.BarChart;

                        break;
                    case "column":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ColumnChart3D;
                            //chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Stack3DColumnChart;
                           
                            //chart.Data.SwapRowsAndColumns = true;
                            //chart.ColorModel.Skin.ApplyRowWise = false;
                            chart.Effects.Enabled = true;
                            chart.Data.ZeroAligned = true;
                            chart.Transform3D.Perspective = 0;
                            chart.Transform3D.XRotation = 130;
                            chart.Transform3D.YRotation = 20;
                            chart.Transform3D.ZRotation = 0;
                        }
                        else
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.ColumnChart;
//                      
                       
                        break;
                    case "doughnut":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.DoughnutChart3D;
                            chart.DoughnutChart3D.OthersCategoryPercent = 0;
                            //chart.DoughnutChart3D.Concentric = true;
                            //chart.DoughnutChart.ConcentricSpacing = 0;
                            //chart.DoughnutChart.ShowConcentricLegend = true;

                            //chart.Data.SwapRowsAndColumns = true;
                            //chart.DoughnutChart3D.PieThickness = 40;
                        }
                        else
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.DoughnutChart;
                            chart.DoughnutChart.OthersCategoryPercent = 0;
                        }
                        chart.Transform3D.XRotation = 50;
                        break;
                    case "funnel":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.FunnelChart3D;
                            chart.FunnelChart3D.OthersCategoryPercent = 0;
                            //chart.Data.SwapRowsAndColumns = true;
                            chart.ColorModel.Skin.ApplyRowWise = true;
                            //chart.FunnelChart3D.Axis = HierarchicalChartAxis.HeightWithRadiusIncrementConstant;
                            chart.FunnelChart3D.Axis = HierarchicalChartAxis.HeightWithSlopeConstant;
                            chart.Data.ZeroAligned = true;
                            chart.Transform3D.Perspective = 0;
                        }
                        else
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.FunnelChart;
                            chart.FunnelChart.OthersCategoryPercent = 0;
                        }
                        break;
                    case "line":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.LineChart3D;
                            chart.LineChart.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Solid;
                            //chart.Transform3D.YRotation = 50;
                            chart.LineChart.HighLightLines = true;
                            //chart.Data.SwapRowsAndColumns = true;
                            chart.Data.ZeroAligned = true;

                            chart.Transform3D.Perspective = 0;
                            chart.Transform3D.XRotation = 125;
                            chart.Transform3D.YRotation = 15;
                            chart.Transform3D.ZRotation = 0;
                        }
                        else
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.LineChart;

                        break;
                    case "pie":
                        chart = new UltraChart();
                        if (is3D)
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.PieChart3D;
                            chart.PieChart3D.OthersCategoryPercent = 0;
                            //chart.PieChart3D.Concentric = true;
                            //chart.PieChart3D.ConcentricSpacing = 0.3;
                            //chart.PieChart3D.ShowConcentricLegend = true;
                        }
                        else
                        {
                            chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.PieChart;
                            chart.PieChart.OthersCategoryPercent = 0;
                        }
                        //chart.Data.SwapRowsAndColumns = true;
                        chart.Transform3D.XRotation = 50;
                        chart.Transform3D.Light = true;
                        break;
                    case "table":
                        Grid = new UltraWebGrid();
                        break;
                    default:
                        break;
                }


                if (chart != null)
                {
                    chart.BackgroundImageStyle = Infragistics.UltraChart.Shared.Styles.ImageFitStyle.StretchedFit;
                    ApplyChartSettings(chart, drWidget);
                    //SetWidgetSource(dt, chart);
                    CreateTable(drWidget, ref htc, chart,frmObj);
                }
                else if (Grid != null)
                {
                    //ApplyGridSettings(ref Grid, drWidget);
                    ApplyGridSettingsNew(ref Grid, drWidget);

                    //SetWidgetSource(dt, Grid);
                    htc.BorderColor = "LightGray";
                    CreateTable(drWidget, ref htc, Grid,frmObj);
                    
                }

            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RenderWidget :" + ex.Message);
        }
        finally
        {
            dt = null;
            HDD = null;
            chart = null;
        }
    }


    /// <summary>
    /// This will create Widget in the referenced HTMLTableCell with source from SQL Query
    /// </summary>
    /// <param name="sql">Query which is the Source of the Widget</param>
    /// <param name="type">Chart Type</param>
    /// <param name="drWidget">DataRow of Widget</param>
    /// <param name="htc">ref HTMLTableCell on which Widget will be rendered</param>
    /// <param name="is3D">Whether to display the data in 2D/3D form</param>
    private void RenderWidget(string sql, string type,DataRow drWidget,ref HtmlTableCell htc,bool is3D,HtmlForm frmObj)
    {
        DataTable dt = new DataTable();
        HDDatabase HDD = new HDDatabase();
        try
        {
            dt = HDD.GetDataTable(sql);
            //RenderWidget(dt, type, drWidget, ref htc, is3D,frmObj);
            RenderWidgetFromMSChart(dt, type, drWidget, ref htc, is3D, frmObj);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : RenderWidget :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    /// <summary>
    /// This will associate the Source to the Widget
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="Chart"></param>
    /// Implemented by 'Imran Gani' on 10-Oct-2012, for MS-Chart Control
    private void SetWidgetSourceForMSChart(DataTable dt, object Chart,ArrayList arrXAxis,ArrayList arrYAxis,DataRow drWidget)
    {
        DataTable dtCloned;
        try
        {
            if (dt != null)
                if (Chart is Chart)
                {
                    //CommonFunctions.decodeData(dt);
                    Chart objChart = (Chart)Chart;
                    if (drWidget != null)
                    {
                        objChart.Annotations.Clear();
                        string type = drWidget["chart_type"].ToString();
                        if (SeriesBindingCharts.Contains(type.Trim().ToLower()))
                        {
                            if (arrYAxis.Count > 0 && dt.Rows.Count > 0)
                            {
                                dtCloned = dt.Clone(); // Added by 'Imran Gani' on 14-Nov-12, to handle numeric x asix.
                                dtCloned.Columns[arrXAxis[0].ToString()].DataType = typeof(string);
                                foreach (DataRow row in dt.Rows)
                                {
                                    dtCloned.ImportRow(row);
                                }
                                for (int i = 0; i < arrYAxis.Count; i++)
                                {
                                    objChart.DataSource = dtCloned;
                                    objChart.Series[i].XValueMember = arrXAxis[0].ToString();
                                    objChart.Series[i].YValueMembers = arrYAxis[i].ToString();
                                    objChart.Series[i].Name = arrYAxis[i].ToString();
                                    objChart.Series[i]["PixelPointDepth"] = "15";
                                    objChart.Series[i]["PixelPointGapDepth"] = "5";
                                    objChart.Series[i]["PointWidth"] = "0.6";
                                    objChart.Series[i].ToolTip = "#VALY";
                                    objChart.Legends[0].Enabled = true;
                                    objChart.DataBind();
                                    if (i < arrYAxis.Count - 1)
                                    {
                                        Series objSeries = new Series();
                                        objSeries.ChartType = objChart.Series[i].ChartType;
                                        objChart.Series.Add(objSeries);
                                    }
                                    objChart.ChartAreas["ChartArea1"].BackColor = System.Drawing.Color.GhostWhite;
                                }
                                objChart.ChartAreas[0].Visible = true;
                            }
                            else
                            {
                                objChart.ChartAreas[0].BackColor = System.Drawing.Color.Transparent;
                                objChart.ChartAreas[0].Visible = false;
                                objChart.Legends[0].Enabled = false;
                                objChart.AlternateText = "Data not available";
                                RectangleAnnotation objAnnotation = new RectangleAnnotation(); // Added by 'Imran Gani' on 05-Dec-12, to empty chart.
                                objAnnotation.AnchorX = 50;
                                objAnnotation.AnchorY = 50;
                                objAnnotation.Text = "Data not available";
                                objAnnotation.ForeColor = Color.Gray;
                                objAnnotation.Font = new Font("Arial", 9);
                                objAnnotation.LineWidth = 1;
                                objAnnotation.LineColor = Color.LightGray;
                                objAnnotation.BackColor = Color.WhiteSmoke;
                                objChart.Annotations.Add(objAnnotation);
                            }
                        }
                        else
                        {
                            objChart.ChartAreas[0].BackColor = System.Drawing.Color.Transparent;
                            if (arrYAxis.Count > 0 && dt.Rows.Count > 0)
                            {
                                objChart.Series[0].Points.DataBind(dt.AsEnumerable(), arrXAxis[0].ToString(), arrYAxis[0].ToString(), "Tooltip=" + arrYAxis[0].ToString());
                                objChart.Legends[0].Enabled = true;
                                objChart.ChartAreas[0].Visible = true;
                            }
                            else
                            {
                                objChart.ChartAreas[0].Visible = false;
                                objChart.Legends[0].Enabled = false;
                                objChart.AlternateText = "Data not available";
                                RectangleAnnotation objAnnotation = new RectangleAnnotation(); // Added by 'Imran Gani' on 05-Dec-12, to empty chart.
                                objAnnotation.AnchorX = 50;
                                objAnnotation.AnchorY = 50;
                                objAnnotation.Text = "Data not available";
                                objAnnotation.ForeColor = Color.Gray;
                                objAnnotation.Font = new Font("Arial", 9);
                                objAnnotation.LineWidth = 1;
                                objAnnotation.LineColor = Color.LightGray;
                                objAnnotation.BackColor = Color.WhiteSmoke;
                                objChart.Annotations.Add(objAnnotation);
                            }
                        }
                    }
                }
                else if (Chart is UltraWebGrid)
                {
                    UltraWebGrid objGrid = (UltraWebGrid)Chart;
                    CommonFunctions.encodeData(dt);
                    HandleDataType4GridTable(dt, drWidget); // Added by 'Imran Gani' on 06-Mar-2014, for MBLocale
                    objGrid.DataSource = dt;
                    objGrid.DataBind();
                    if (dt.Rows.Count < 1)
                        objGrid.DisplayLayout.NoDataMessage = "Data not available";
                }
            
        }
        catch(Exception ex)
        {
            if (Chart is Chart)
            {
                Chart objChart = (Chart)Chart;
                objChart.ChartAreas["ChartArea1"].BackColor = System.Drawing.Color.Transparent;
                objChart.Legends[0].Enabled = false;
            }
            LogWriter.WriteLog("Error : SetWidgetSourceForMSChart :" + ex.Message);
        }
    }

    /// <summary>
    /// This will associate the Source to the Widget
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="Chart"></param>
    private void SetWidgetSource(DataTable dt, object Chart, ArrayList arrXAxis, ArrayList arrYAxis, DataRow drWidget)
    {
        try
        {
            if (dt != null)
                if (Chart is UltraChart)
                {
                    UltraChart objChart = (UltraChart)Chart;
                    //objChart.FillSceneGraph += new Infragistics.UltraChart.Shared.Events.FillSceneGraphEventHandler(objChart_FillSceneGraph);
                    if (drWidget != null)
                    {
                        string type = drWidget["chart_type"].ToString();
                        if (SeriesBindingCharts.Contains(type))
                        {
                            if (arrYAxis.Count > 0)
                            {
                                if (objChart.Series.Count > 0)
                                {
                                    int index = objChart.Series.Count - 1;
                                    for (int j = index; j <= index && j > -1; j--)
                                    {
                                        if (j > -1)
                                        {
                                            objChart.Series.RemoveAt(j);
                                        }
                                    }
                                }
                                for (int i = 0; i < arrYAxis.Count; i++)
                                {
                                    NumericSeries Series = new NumericSeries(objChart);
                                    Series.Data.DataSource = dt;
                                    Series.Data.LabelColumn = arrXAxis[0].ToString();
                                    Series.Data.ValueColumn = arrYAxis[i].ToString();
                                    Series.Label = arrYAxis[i].ToString();
                                    Series.DataBind();
                                    objChart.Series.Add(Series);
                                    objChart.Data.DataBind();
                                }
                            }
                            else
                            {
                                objChart.Data.SwapRowsAndColumns = true;
                                objChart.DataSource = dt;
                                if (dt.Rows.Count < 1)
                                    objChart.EmptyChartText = "Data not available";
                                objChart.DataBind();
                            }
                        }
                        else
                        {
                            objChart.DataSource = dt;
                            if (dt.Rows.Count < 1)
                                objChart.EmptyChartText = "Data not available";
                            objChart.DataBind();
                        }
                    }
                }
                else if (Chart is UltraWebGrid)
                {
                    UltraWebGrid objGrid = (UltraWebGrid)Chart;
                    objGrid.DataSource = dt;
                    objGrid.DataBind();
                    if (dt.Rows.Count < 1)
                        objGrid.DisplayLayout.NoDataMessage = "Data not available";
                }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SetWidgetSource :" + ex.Message);
        }
    }

    #region Fill Graphscene
    //void objChart_FillSceneGraph(object sender, Infragistics.UltraChart.Shared.Events.FillSceneGraphEventArgs e)
    //{
    //    //throw new Exception("The method or operation is not implemented.");

    //    PrimitiveCollection primitivesToAdd = new PrimitiveCollection();
    //    foreach (Primitive p in e.SceneGraph)
    //    {
    //        if (p.Path != null && p.Path.Contains("Legend"))
    //        {
    //            if (p.Path.Contains("Legend"))
    //            {
    //                p.Layer = e.ChartCore.GetChartLayer();
    //                if (p is Box)
    //                {
    //                    this.LastPrimitive = p;
    //                    p.Caps |= PCaps.HitTest | PCaps.Tooltip;

    //                }
    //                else if (p is Text)
    //                {
    //                    Text t = (Text)p;
    //                    p.Row = this.LastPrimitive.Row;
    //                    p.Column = this.LastPrimitive.Column;
    //                    p.Value = this.LastPrimitive.Value;
    //                    Box newBox = new Box(t.bounds);
    //                    newBox.PE.FillOpacity = newBox.PE.StrokeOpacity = 0;
    //                    newBox.Row = p.Row;
    //                    newBox.Column = p.Column;
    //                    newBox.Chart = p.Chart;
    //                    newBox.Layer = p.Layer;
    //                    newBox.Value = p.Value;
    //                    newBox.Caps = PCaps.HitTest | PCaps.Tooltip;
    //                    primitivesToAdd.Add(newBox);
    //                }
    //            }
    //        }
    //    }
    //    e.SceneGraph.AddRange(primitivesToAdd.ToArray());
    //}
    #endregion

    /// <summary>
    /// This function will Create the Widgets in the ref HTMLTableCEll
    /// </summary>
    /// <param name="drWidgets"></param>
    /// <param name="htcResult"></param>
    /// <param name="Chart"></param>
    private void CreateTable(DataRow drWidgets,ref HtmlTableCell htcResult,object Chart,HtmlForm frmObj)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            HtmlTable ht = new HtmlTable();
            //ht.Width = "100%"; //Jun 3 2010
            if (Chart is UltraWebGrid) // Modified by 'Imran Gani' on 30-Nov-12, to aline the table grid.
            {
                if (!HttpContext.Current.Request.Url.AbsoluteUri.ToString().Contains("DashboardDesigner.aspx?")) // Added by 'Imran Gani' on 06-Mar-2014, for handling width
                    ht.Width = "100%";
                ht.Style.Add("table-layout", "fixed");
            }
            ht.CellPadding = 0;
            ht.CellSpacing = 0;
            ht.Border = 0;
            HtmlTableRow htr = new HtmlTableRow();
            HtmlTableCell htc = new HtmlTableCell();
            htc.NoWrap = true;
            if (Chart != null)
            {
                if (drWidgets != null)
                {

                    #region Header Text
                    htr = new HtmlTableRow();
                    htc = new HtmlTableCell();
                    htc.NoWrap = true;
                    htc.ColSpan = 2; // Added by 'Imran Gani' on 30-Nov-12, to aline the table grid.

                    Hashtable htParam = new Hashtable();
                    DataRow drInput = null;
                    if (drWidgets["source_type"].ToString().ToLower() == "query")
                    {
                        DataRow drSQL = HDD.GetTableRow("select * from sy_report_sql where af_row_id = '" + drWidgets["source"].ToString() + "'");
                        if (drSQL != null)
                        {
                            //decode added by Sampath on 27-Apr-2012
                            //CommonFunctions.decodeData(drSQL);
                            //GetParametersInHashTable(ref htParam, drSQL["report_base_sql"].ToString(), drSQL);
                            BuildParameters BP = new BuildParameters();
                            //htParam = BP.updateParameters(drSQL["report_base_sql"].ToString(), drSQL["report_base_param"].ToString(), frmObj, drWidgets["af_row_id"].ToString());
                            BP.GetParametersInHashTable(drSQL["report_base_sql"].ToString(), drSQL["report_base_param"].ToString(), ref htParam);
                            drInput = drSQL;
                        }
                    }
                    else if (drWidgets["source_type"].ToString().ToLower() == "report")
                    {
                        DataRow drSQL = HDD.GetTableRow("select * from sy_report where af_row_id = '"+drWidgets["source"].ToString()+"'");
                        if (drSQL != null)
                        {
                            if (drSQL["rpt_base_object"].ToString().ToLower() == "true" || drSQL["rpt_base_object"].ToString().ToLower() == "sql")
                            {
                                DataRow drrSQL = HDD.GetTableRow("select * from sy_report_sql where report_base_id =(select top 1 object_id from sy_report_att where rpt_id = '" + drSQL["af_row_id"].ToString() + "')");
                                if (drrSQL != null)
                                {
                                    //decode added by Sampath on 27-Apr-2012
                                    //CommonFunctions.decodeData(drrSQL);
                                    //GetParametersInHashTable(ref htParam, drrSQL["report_base_sql"].ToString(), drrSQL);
                                    BuildParameters BP = new BuildParameters();
                                    //htParam = BP.updateParameters(drSQL["report_base_sql"].ToString(), drSQL["report_base_param"].ToString(), frmObj, drWidgets["af_row_id"].ToString());
                                    BP.GetParametersInHashTable(drrSQL["report_base_sql"].ToString(), drrSQL["report_base_param"].ToString(), ref htParam);
                                    drInput = drrSQL;
                                }
                            }
                        }
                    }


                    HtmlTable htheader = new HtmlTable();
                    htheader.CellPadding = 0;
                    htheader.CellSpacing = 0;
                    htheader.Border = 0;
                    htheader.Width = "100%";
                    HtmlTableRow htrheader = new HtmlTableRow();
                    HtmlTableCell htcheader = new HtmlTableCell();
                    htcheader.NoWrap = true;

                    Label lblHeader = new Label();
                    lblHeader.Text = HttpUtility.HtmlEncode(drWidgets["header"].ToString());
                    htcheader.Controls.Add(new LiteralControl("&nbsp;")); // Added by 'Imran Gani' on 25-Jun-2012, to have a space in the header.
                    htcheader.Controls.Add(lblHeader);
                    htcheader.Attributes.Add("class", "Grid_Header");
                    htrheader.Controls.Add(htcheader);
                    htcheader = new HtmlTableCell();
                    htcheader.NoWrap = true;
                    if (drInput != null)
                    {
                        AddParameterIcon(ref htcheader, drWidgets, drInput, htParam);
                        //AddParameters(ref htcheader, drWidgets, drInput, htParam, frmObj);

                    }
                    else
                        getHeaderIcons(ref htcheader, drWidgets); // Added by 'Imran Gani' on 21-Jun-2012, to get the header icons.
                    htcheader.Align = "right";
                    htrheader.Controls.Add(htcheader);
                    htheader.Controls.Add(htrheader);
                    
                    
                    
                    HtmlTable ht1 = new HtmlTable();
                    ht1.Width = "100%";
                    ht1.CellPadding = 0;
                    ht1.CellSpacing = 0;
                    ht1.Border = 0;
                    HtmlTableRow htr1 = new HtmlTableRow();
                    HtmlTableCell htc1 = new HtmlTableCell();
                    //htc1.Controls.Add(lblHeader);
                    htc1.NoWrap = true;
                    htc1.Attributes.Add("class", "Grid_Header");
                    htc1.Controls.Add(htheader);
                    htr1.Controls.Add(htc1);
                    //Literal lit = new Literal();
                    //lit.Text = "&nbsp;";
                    if(drInput!=null)
                        AddParameters(ref htcheader, drWidgets, drInput, htParam, frmObj);
                    //htc.Controls.Add(lit);
                    //Previous place where parameters are added
                    
                    ht1.Controls.Add(htr1);
                    htc.Controls.Add(ht1);
                    htr.Controls.Add(htc);
                    ht.Controls.Add(htr);
                    #endregion

                    #region Create Parameter Controls
                    //htr1 = new HtmlTableRow();
                    //htc1 = new HtmlTableCell();
                    //if(drInput!=null)
                    //    AddParameters(ref htc1, drWidgets, drInput, htParam);
                    ////htc1.Controls.Add(lbl);
                    //htr1.Controls.Add(htc1);
                    //ht.Controls.Add(htr1);
                    #endregion


                    #region AddChart
                    htr = new HtmlTableRow();
                    htc = new HtmlTableCell();
                    htc.ID = "td_WidgetChart_" + drWidgets["af_row_id"].ToString();
                    htc.NoWrap = true;
                    htc.ColSpan = 2;

                    string strSQL = "";
                    DataTable dtWidgetData = new DataTable();
                    

                    //XY Axis changes
                    ArrayList arrXAxis = new ArrayList();
                    ArrayList arrYAxis = new ArrayList();
                    //


                    GetWidgetData(drWidgets, ref strSQL, ref dtWidgetData,frmObj,ref arrXAxis,ref arrYAxis);
                    SetWidgetSourceForMSChart(dtWidgetData, Chart, arrXAxis, arrYAxis, drWidgets); // Added by 'Imran Gani' on 10-Oct-2012, to create chart from MS-chart control.
                    //SetWidgetSource(dtWidgetData, Chart, arrXAxis, arrYAxis, drWidgets);

                    // Below lines are added by 'Imran Gani' on 28-Jun-2012, to display the widgets report in a data grid view.
                    string sCurrentUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
                    if (sCurrentUrl.Contains("WidgetsView.aspx?"))
                    {
                        if (Chart is Chart) // Added by 'Imran Gani' on 06-Mar-2014, for MBLocale
                            HandleDataType4GridTable(dtWidgetData, drWidgets);
                        DisplayDataGrid(dtWidgetData, ref frmObj);
                    }

                    //if (Chart is UltraChart)
                    if (Chart is Chart)
                    {
                        //UltraChart ObjChart = (UltraChart)Chart;
                        Chart ObjChart = (Chart)Chart;
                        ObjChart.BorderlineColor = System.Drawing.Color.LightGray;
                        //ObjChart.Border.Color = System.Drawing.Color.LightGray;
                        //ObjChart.EmptyChartText = "Data not Available";
                        htc.Controls.Add(ObjChart);
                        htr.Controls.Add(htc);
                        ht.Controls.Add(htr);

                    }
                    else if (Chart is UltraWebGrid)
                    {
                        UltraWebGrid objGrid = (UltraWebGrid)Chart;
                        objGrid.BorderColor = System.Drawing.Color.LightGray;
                        objGrid.BorderStyle = BorderStyle.Solid;
                        objGrid.BorderWidth = Unit.Pixel(1);
                        htc.Controls.Add(objGrid);
                        #region Old Line Commented 'Imran Gani' on 07-Aug-2014, for Table Grid Layout settings
                        //objGrid
                        //Label lbl = new Label();
                        ////lbl.Width = Unit.Percentage(100); //Jun 3 2010
                        ////lbl.Style.Add("min-width", "1000px"); // Commanded by 'Imran Gani' on 07-Nov-12, to aline the table grid.
                        //lbl.Height = Unit.Percentage(100); //Jun 3 2010
                        //lbl.BorderColor = Color.LightGray;
                        //lbl.BorderWidth = Unit.Pixel(1);
                        //lbl.Controls.Add(objGrid);
                        //htc.Controls.Add(lbl);
                        #endregion
                        htr.Controls.Add(htc);
                        ht.Controls.Add(htr);
                    }
                    #endregion
                }




            }

            if (ht.Controls.Count > 0)
                htcResult.Controls.Add(ht);


        }
        catch
        {
        }
        finally
        {
            HDD = null;
        }
    }

    /// <summary>
    /// To get the Icon on the top right of the Header.
    /// </summary>
    /// <param name="drInput"></param>
    /// <param name="drWidgets"></param>
    /// <returns>HtmlTableCell with Icons</returns>
    private void getHeaderIcons(ref HtmlTableCell htcHeaderIcons, DataRow drWidgets)  // Added by 'Imran Gani' on 21-Jun-2012, to get the header icons.
    {
        try
        {
            htcHeaderIcons.NoWrap = true;
            
            string sCurrentUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
            if (!sCurrentUrl.Contains("WidgetsView.aspx?"))
            {
                string sTempUrl = sCurrentUrl.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf('/') + 1);
                HyperLink href = new HyperLink();
                href.ID = "btnPopupData" + drWidgets["af_row_id"].ToString();
                href.ImageUrl = "Images/table-export-icon-16.png";
                href.ToolTip = "Data Result Display";
                href.Target = "_Blank";
                href.NavigateUrl = sTempUrl + "WidgetsView.aspx?pgs_id=49288f21587a5a7c&pk=" + drWidgets["af_row_id"].ToString() + "&Action=data";
                href.Attributes.Add("onclick", "javascript:passWidgetParameter(this);"); // Added by 'Imran Gani' on 01-Aug-2013, to include parameter values in URL
                
                htcHeaderIcons.Controls.Add(href);
                htcHeaderIcons.Controls.Add(new LiteralControl("&nbsp;"));
                
                href = new HyperLink();
                href.ID = "btnPopupWgt" + drWidgets["af_row_id"].ToString();
                href.ImageUrl = "Images/newWindow21.gif";
                href.ToolTip = "Larger Widgets View";
                href.Target = "_Blank";
                href.NavigateUrl = sTempUrl + "WidgetsView.aspx?pgs_id=49288f21587a5a7c&pk=" + drWidgets["af_row_id"].ToString() + "&Action=view";
                href.Attributes.Add("onclick", "javascript:passWidgetParameter(this);"); // Added by 'Imran Gani' on 01-Aug-2013, to include parameter values in URL
                
                htcHeaderIcons.Controls.Add(new LiteralControl("&nbsp;"));    
                htcHeaderIcons.Controls.Add(href);
            }
            htcHeaderIcons.Controls.Add(new LiteralControl("&nbsp;"));

            htcHeaderIcons.Attributes.Add("class", "Grid_Header");
            htcHeaderIcons.Align = "Right";
        }
        catch (Exception e)
        {
        }
        finally
        {
        }
    }
    private void ApplyGridSettings(ref Infragistics.WebUI.UltraWebGrid.UltraWebGrid objGrid, DataRow drWidget)
    {
        try
        {
            if (objGrid != null)
            {
                //UltraWebGrid objGrid = (UltraWebGrid)Grid;
                //objGrid.Width = Unit.Percentage(100);
                objGrid.ID = "wgt_"+drWidget["af_row_id"].ToString();
                objGrid.Width = Unit.Pixel(800);
                //objGrid.BorderStyle = BorderStyle.Solid;
                objGrid.GridLines = UltraGridLines.Both;
                objGrid.CellPadding = 0;
                objGrid.CellSpacing = 0;
               

                //string strRowColor = getCSSPropertyValue("Grid_Row1", "background-color");
                string strHeaderColor = getCSSPropertyValue("Grid_Header", "background-color");
                //objGrid.DisplayLayout.HeaderStyleDefault.BackColor = System.Drawing.Color.FromName(strHeaderColor);
                //objGrid.DisplayLayout.HeaderStyleDefault.CssClass = "controlLabelFont";
                //objGrid.DisplayLayout.RowStyleDefault.CssClass = "controlFont";
                //objGrid.DisplayLayout.RowAlternateStyleDefault.BackColor = System.Drawing.Color.FromName(strRowColor);

                objGrid.DisplayLayout.ScrollBarView = ScrollBarView.Both;
                //objGrid.DisplayLayout.ScrollBar = ScrollBar.Auto;

                objGrid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;
                
                

                

                
                //objGrid.DisplayLayout.SelectTypeRowDefault = SelectType.Extended;
                objGrid.DisplayLayout.AllowColSizingDefault = AllowSizing.Free;
                objGrid.DisplayLayout.AllowDeleteDefault = AllowDelete.Yes;
                //objGrid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;
                objGrid.DisplayLayout.StationaryMarginsOutlookGroupBy = true;
                objGrid.DisplayLayout.ViewType = ViewType.Hierarchical;
                objGrid.DisplayLayout.RowSizingDefault = AllowSizing.Free;
                objGrid.DisplayLayout.TableLayout = TableLayout.Fixed;
                objGrid.DisplayLayout.NoDataMessage = "No Data Available";
                objGrid.DisplayLayout.RowHeightDefault = Unit.Pixel(23);
                objGrid.DisplayLayout.FrameStyle.BorderColor = Color.LightGray;
                objGrid.DisplayLayout.FrameStyle.BorderWidth = Unit.Pixel(1);
                objGrid.DisplayLayout.FrameStyle.Height = Unit.Pixel(300);
                //objGrid.DisplayLayout.FrameStyle.Width = Unit.Percentage(100); //commented for testing
                objGrid.DisplayLayout.Grid.Width = Unit.Percentage(100);
                objGrid.DisplayLayout.Grid.Height = Unit.Pixel(300);
                objGrid.DisplayLayout.Grid.BorderColor = System.Drawing.Color.LightGray;
                objGrid.DisplayLayout.Grid.CellPadding = 0;// 1;
                objGrid.DisplayLayout.Grid.CellSpacing = 0;// 1;


                objGrid.Load += new EventHandler(objGrid_Load);

                //objGrid.DisplayLayout.Grid.Rows.Band.RowStyle.CssClass = "controlFont";
                objGrid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;



                objGrid.DisplayLayout.RowStyleDefault.CssClass = "controlFont";
                objGrid.DisplayLayout.RowAlternateStyleDefault.CssClass = "Grid_Row1";
                objGrid.DisplayLayout.Rows.Band.RowStyle.CssClass = "controlFont";
                
                //objGrid.DisplayLayout.HeaderStyleDefault.CssClass = "controlLabelFont";
                //objGrid.DisplayLayout.HeaderStyleDefault.BackColor = Color.Red;//Color.FromName(strHeaderColor);

                //objGrid.Columns.Band.HeaderStyle.CssClass = "Grid_header";

                //objGrid.Columns.Band.HeaderStyle.BackColor = Color.Red;

                

               
                

            }
        }
        catch
        {
        }
    }

    void objGrid_Load(object sender, EventArgs e)
    {
       UltraWebGrid grid = (UltraWebGrid)sender;
       string strHeaderColor = getCSSPropertyValue("Grid_Header", "background-color");
       string strForeColor = getCSSPropertyValue("Grid_Header", "COLOR");
       grid.DisplayLayout.HeaderStyleDefault.BackColor = Color.FromName(strHeaderColor);
       grid.DisplayLayout.HeaderStyleDefault.ForeColor = Color.FromName(strForeColor);

       string strAlternateColor = getCSSPropertyValue("Grid_Row1", "background-color");

       grid.DisplayLayout.RowAlternateStyleDefault.BackColor = Color.FromName(strAlternateColor);

       //grid.DisplayLayout.Grid.BorderStyle = BorderStyle.Solid;
       grid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;
       //grid.DisplayLayout.AllowColumnMovingDefault = AllowColumnMoving.OnClient;
       grid.DisplayLayout.TableLayout = TableLayout.Fixed;
       grid.DisplayLayout.Grid.DisplayLayout.TableLayout = TableLayout.Fixed;
       grid.DisplayLayout.FrameStyle.Font.Size = FontUnit.XXSmall;
       grid.DisplayLayout.FrameStyle.Font.Name = "Arial";

       //grid.Style.Add("min-width", "1000px");
       //grid.DisplayLayout.Grid.Style.Add("min-width", "1000px");

       #region Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
       int width = 400;
       int height = 300;
       int screenWidth = 1600;
       //screenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width - 70; // Will give server screen width size
       if (dtWidgetProperty != null && dtWidgetProperty.Rows.Count > 0)
       {
           DataRow[] dr = dtWidgetProperty.Select("widget = '" + grid.ID.Substring(grid.ID.LastIndexOf("_") + 1) + "'");
           if (dr.Length > 0)
           {
               if (dr[0]["fullview"].ToString().ToLower() == "true")
               {
                   grid.Width = Unit.Pixel(screenWidth);
                   int GridHeight = grid.Rows.Count * Convert.ToInt32(grid.DisplayLayout.RowHeightDefault.Value);
                   if (GridHeight < 300) // to set the height of grid based on 
                       grid.Height = Unit.Pixel(GridHeight + 30);
               }
               else if (dr[0]["widget_size"].ToString().ToLower() == "small")
               {
                   width = ((screenWidth / dashboardColumns) / 2) - 5;
                   height = Convert.ToInt32(width * 0.55);
                   grid.Width = Unit.Pixel(width);
                   grid.Height = Unit.Pixel(height);
               }
               else
               {
                   width = screenWidth / dashboardColumns - 2;
                   height = Convert.ToInt32(width * 0.65);
                   grid.Width = Unit.Pixel(width);
                   grid.Height = Unit.Pixel(height);
               }
           }
           else
           {
               width = screenWidth / dashboardColumns - 2;
               height = Convert.ToInt32(width * 0.65);
               grid.Width = Unit.Pixel(width);
               grid.Height = Unit.Pixel(height);
           }
       }
       else
       {
           width = screenWidth / dashboardColumns - 2;
           height = Convert.ToInt32(width * 0.65);
           grid.Width = Unit.Pixel(width);
           grid.Height = Unit.Pixel(height);
       }
       
       if (bWidgetPage)
       {
           grid.Width = Unit.Pixel(screenWidth);
           grid.Height = Unit.Pixel(500);
       }
       grid.Browser = BrowserLevel.UpLevel; // Added by 'Imran Gani' on 08-Nov-12, for proper UI in all browsers
       #endregion
        //grid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;

       ////ApplyGridSettingsNew(ref grid, null);
       
    }

    /// <summary>
    /// To Apply the chart settings of rendering.
    /// </summary>
    /// <param name="chart">Ms-Chart</param>
    /// <param name="drWidget">DataRow of widget</param>
    /// Implemented by 'Imran Gani' by 10-Oct-2012, for MS-Chart control
    private void ApplyMSChartSettings(object chart, DataRow drWidget)
    {
        Legend objLegend = new Legend();
        try
        {
            if (chart is Chart)
            {
                Chart ObjChart = (Chart)chart;
                ObjChart.ID = "wgt_" + drWidget["af_row_id"].ToString();
                ObjChart.RenderType = RenderType.ImageTag;
                ObjChart.Style.Add(HtmlTextWriterStyle.ZIndex, "-4");
                objLegend.BorderColor = System.Drawing.Color.LightGray;
                ObjChart.Legends.Add(objLegend);

                #region Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
                int width = 400;
                int height = 300;
                getWidthHeight4Chart(ref width, ref height, drWidget);
                
                // Below width & height are added by 'Imran Gani' on 22-Jun-2012, to set the chart size.
                string sTempUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
                if (!sTempUrl.Contains("WidgetsView.aspx?"))
                {
                    ObjChart.Width = Unit.Pixel(width);
                    ObjChart.Height = Unit.Pixel(height);
                }
                else
                {
                    height = Convert.ToInt32(width * 0.45);
                    ObjChart.Width = Unit.Pixel(width);
                    ObjChart.Height = Unit.Pixel(height);
                }
                #endregion
                ObjChart.BackColor = System.Drawing.Color.White;
                ObjChart.BorderlineColor = System.Drawing.Color.LightGray;
                ObjChart.BorderlineDashStyle = ChartDashStyle.Solid;
                ObjChart.BorderlineWidth = 1;
                ObjChart.ChartAreas["ChartArea1"].AxisY.IntervalAutoMode = IntervalAutoMode.VariableCount;
                ObjChart.ChartAreas["ChartArea1"].AxisY.IntervalType = DateTimeIntervalType.Auto;
                ObjChart.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = true;
                ObjChart.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = System.Drawing.Color.LightGray;
                ObjChart.ChartAreas["ChartArea1"].AxisY.MajorTickMark.LineColor = System.Drawing.Color.LightGray;
                ObjChart.ChartAreas["ChartArea1"].AxisY.LineColor = System.Drawing.Color.LightGray;
                ObjChart.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = true;
                ObjChart.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = System.Drawing.Color.LightGray;
                ObjChart.ChartAreas["ChartArea1"].AxisX.LineColor = System.Drawing.Color.LightGray;
                ObjChart.ChartAreas["ChartArea1"].AxisX.MajorTickMark.LineColor = System.Drawing.Color.LightGray;
                //ObjChart.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ApplyMSChartSettings :" + ex.Message);
        }
        finally
        {}
    }

    private void ApplyChartSettings(object chart,DataRow drWidget)
    {
        try
        {
            if (chart is UltraChart)
            {
                UltraChart ObjChart = (UltraChart)chart;
                ObjChart.ID = "wgt_"+drWidget["af_row_id"].ToString();
                ObjChart.DeploymentScenario.Scenario = Infragistics.UltraChart.Shared.Styles.ImageDeploymentScenario.Session;
                ObjChart.DeploymentScenario.RenderingType = Infragistics.UltraChart.Shared.Styles.RenderingType.Image;
                //ObjChart.DeploymentScenario.RenderingType = Infragistics.UltraChart.Shared.Styles.RenderingType.Flash;
                ObjChart.Style.Add(HtmlTextWriterStyle.ZIndex, "-4");
                ObjChart.Legend.BorderColor = System.Drawing.Color.LightGray;

                // Below width & height are added by 'Imran Gani' on 22-Jun-2012, to set the chart size.
                string sTempUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
                if (!sTempUrl.Contains("WidgetsView.aspx?"))
                {
                    ObjChart.Width = Unit.Percentage(100);
                    //ObjChart.Height = Unit.Percentage(100);
                }
                else
                {
                    ObjChart.Width = Unit.Pixel(900);
                    ObjChart.Height = Unit.Pixel(450);
                }
                ObjChart.Tooltips.Display = Infragistics.UltraChart.Shared.Styles.TooltipDisplay.MouseMove;
                ObjChart.InvalidDataReceived += new Infragistics.UltraChart.Shared.Events.ChartDataInvalidEventHandler(ObjChart_InvalidDataReceived);
                ObjChart.ChartDrawItem += new Infragistics.UltraChart.Shared.Events.ChartDrawItemEventHandler(ObjChart_ChartDrawItem);
                //ObjChart.ColorModel.ModelStyle = Infragistics.UltraChart.Shared.Styles.ColorModels.CustomLinear;
                //ObjChart.ColorModel.CustomPalette = ColorPalette();
                
                ObjChart.ColorModel.ModelStyle = Infragistics.UltraChart.Shared.Styles.ColorModels.CustomSkin;
                ObjChart.ColorModel.Skin.PaintElement = CustomPaintElements();
                //ObjChart.ColorModel.ModelStyle = ColorModels.PureRandom;
                ObjChart.ColorModel.Scaling = ColorScaling.Oscillating;
                ObjChart.ColorModel.AlphaLevel = 150;

                ObjChart.Data.ZeroAligned = true;
                
                
                if (drWidget != null)
                {
                    ObjChart.Legend.Visible = drWidget["show_legend"].ToString().Trim() != "" ? Convert.ToBoolean(drWidget["show_legend"].ToString()) : false;
                    if (drWidget["legend_position"].ToString().Trim() != "")
                    {
                        switch (drWidget["legend_position"].ToString().ToLower())
                        {
                            case "left":
                                ObjChart.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Left;
                                break;
                            case "right":
                                ObjChart.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Right;
                                break;
                            case "top":
                                ObjChart.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Top;
                                break;
                            case "bottom":
                                ObjChart.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Bottom;
                                break;
                            default:
                                ObjChart.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Right;
                                break;
                        }

                    }

                    //if (drDashboard["empty_chart_text"].ToString() != "")
                    //{
                      //  ObjChart.EmptyChartText = drDashboard["empty_chart_text"].ToString();
                    //}



                    
                }
            }
        }
        catch
        {

        }
    }

    void ObjChart_ChartDrawItem(object sender, Infragistics.UltraChart.Shared.Events.ChartDrawItemEventArgs e)
    {
        Infragistics.UltraChart.Core.Primitives.Primitive prv = e.Primitive;

        //Infragistics.UltraChart.Render.ChartRender render = (Infragistics.UltraChart.Render.ChartRender)sender;
        //render.chartImage.Width = 1000;
        //render.chartImage.Height = 1000;
        //render.chartImage.Size.Width = 1000;
        //render.chartImage.Size.Height = 1000;

        
    }

    void ObjChart_InvalidDataReceived(object sender, Infragistics.UltraChart.Shared.Events.ChartDataInvalidEventArgs e)
    {
        e.LabelStyle.FontColor = System.Drawing.Color.Black;
        e.LabelStyle.VerticalAlign = System.Drawing.StringAlignment.Center;
        e.LabelStyle.WrapText = true;
        e.LabelStyle.HorizontalAlign = System.Drawing.StringAlignment.Center;
        e.LabelStyle.Font = new System.Drawing.Font("Arial", 1.6f);
        //e.LabelStyle.Font.
        e.Text = "Data not Available";
        
    }


    public void GenerateWidgets(string strDBafrowid,ref HtmlTableCell htcResult,bool is3D,HtmlForm frmObj,bool bCheckActiveStatus)
    {
        HDDatabase HDD = new HDDatabase();
        DataTable dt = new DataTable();
        try
        {
            if (strDBafrowid.Trim() != "")
            {
                string sql = "select * from sy_widgets where af_row_id = '"+strDBafrowid+"'";
                dt = HDD.GetDataTable(sql);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                       // string strDBSQL = GetDashboardSQL(dr);
                        string strDBSQL = "";

                        is3D = dr["chart_type"].ToString().Contains("3D") ? true : false; // Added by 'Imran Gani' on 01-Nov-2012,
                        if (bCheckActiveStatus)
                        {
                            if (dr["active"].ToString() != "" ? Convert.ToBoolean(dr["active"].ToString()) : false)
                            {
                                DataTable dtWidgetData = new DataTable();
                                //GetWidgetData(dr, ref strDBSQL, ref dtWidgetData, frmObj);
                                //RenderWidget(dtWidgetData, dr["chart_type"].ToString(), dr, ref htcResult, is3D,frmObj);
                                RenderWidgetFromMSChart(dtWidgetData, dr["chart_type"].ToString(), dr, ref htcResult, is3D, frmObj); // Implemented by 'Imran Gani' on 10-Oct-2012, for MS-Chart Control
                            }
                            else
                            {
                                RenderNonActiveWidget(ref htcResult, dr["name"].ToString(), dr["header"].ToString());
                            }
                        }
                        else
                        {
                            bWidgetPage = true;
                            DataTable dtWidgetData = new DataTable();
                            //GetWidgetData(dr, ref strDBSQL, ref dtWidgetData, frmObj);
                            //RenderWidget(dtWidgetData, dr["chart_type"].ToString(), dr, ref htcResult, is3D, frmObj);
                            RenderWidgetFromMSChart(dtWidgetData, dr["chart_type"].ToString(), dr, ref htcResult, is3D, frmObj); // Implemented by 'Imran Gani' on 10-Oct-2012, for MS-Chart Control
                        }

                        htcResult.Attributes.Add("title", dr["description"].ToString());
                        
                    }
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GenerateWidgets :" + ex.Message);
        }
        finally
        {
            HDD = null;
            dt = null;
        }
    }
    private void RenderNonActiveWidget(ref HtmlTableCell htc,string Name,string header)
    {
        try
        {
            HtmlTable ht1 = new HtmlTable();
            ht1.Width = "100%";
            HtmlTableRow htr1 = new HtmlTableRow();
            HtmlTableCell htc1 = new HtmlTableCell();

            Label lbl = new Label();
            lbl.Text = header;
            htc1.Controls.Add(lbl);
            htc1.Attributes.Add("class", "Grid_Header");
            htr1.Controls.Add(htc1);
            ht1.Controls.Add(htr1);


            htc1 = new HtmlTableCell();
            htr1 = new HtmlTableRow();
            htc1.VAlign = "Center";
            htc1.Align = "center";
            lbl = new Label();
            lbl.Text = "The widget \"" + Name + "\" is inactive.";
            lbl.CssClass = "controlLabelFont";
            lbl.BorderColor = Color.LightGray;
            lbl.BorderWidth = Unit.Pixel(1);
            lbl.Height = Unit.Pixel(300);
            lbl.Width = Unit.Percentage(100);
            htc1.Controls.Add(lbl);
            htr1.Controls.Add(htc1);
            ht1.Controls.Add(htr1);

            htc.BorderColor = "LightGray";

            //lbl = new Label();
            //lbl.BorderColor = Color.LightGray;
            //lbl.BorderStyle = BorderStyle.Solid;
            //lbl.BorderWidth = Unit.Pixel(1);
            //lbl.Controls.Add(ht1);

            htc.Controls.Add(ht1);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : RenderNonActiveWidget : "+ex.Message);
        }
    }


    public string getCSSPropertyValue(string ClassName, string Property)
    {
        string sValue = "";
        string sCSSContent = getCSSContent();
        if (sCSSContent != "")
        {
            string sCSSClass = getCSSClass(sCSSContent, ClassName);
            if (sCSSClass != "")
            {
                int iStart = 0;
                int iEnd = 0;

                if (sCSSClass.Contains(Property))
                {
                    iStart = sCSSClass.IndexOf(Property);
                    iStart = sCSSClass.IndexOf(":", iStart);
                    iStart = iStart + 1;
                    iEnd = sCSSClass.IndexOf(";", iStart + 1);
                    sValue = sCSSClass.Substring(iStart, iEnd - iStart);
                }
            }
        }
        return sValue;
    }


    private string getCSSContent()
    {
        string sFilePath = HttpContext.Current.Server.MapPath(".") + @"\App_Themes\" + HttpContext.Current.Session["theme"].ToString() + "\\" + HttpContext.Current.Session["theme"].ToString().ToLower().Replace("theme", "") + ".css";
        string sCSSContent = "";
        StreamReader sr;

        if (File.Exists(sFilePath))
        {
            sr = File.OpenText(sFilePath);
            sCSSContent = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
        }
        return sCSSContent;
    }

    private string getCSSClass(string CSSContent, string ClassName)
    {
        //ClassName = ClassName +"\r\n{\r\n";//ClassName = "." + ClassName + "\r\n{\r\n";
        int iStart = 0;
        int iEnd = 0;
        string sCSSClass = "";
        if (CSSContent.Contains(ClassName))
        {
            iStart = CSSContent.IndexOf(ClassName);
            iEnd = CSSContent.IndexOf("}", iStart);
            sCSSClass = CSSContent.Substring(iStart + ClassName.Length, iEnd - iStart - ClassName.Length);
        }

        return sCSSClass;
    }
    /// <summary>
    /// This will fill the hashtable with columns and their display names
    /// </summary>
    /// <param name="htCaptions">Reference Hashtable to which fields should be added</param>
    /// <param name="dtSource">DataTable which has the Columns and their Captions</param>
    private void HashColumnNames(ref Hashtable htCaptions,DataTable dtSource)
    {
        try
        {
            if(dtSource!=null)
                if(dtSource.Rows.Count>0)
                    foreach (DataRow dr in dtSource.Rows)
                    {
                        if (!htCaptions.Contains(dr["attrib_id"].ToString()))
                        {
                            htCaptions.Add(dr["attrib_id"].ToString(),dr["caption"].ToString());
                        }
                    }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : HashColumnNames :"+ ex.Message);
        }
    }

    private DataTable ReplaceColumnCaptions(Hashtable htCaptions, ref DataTable dtSource)
    {
        if(htCaptions!=null)
            if (htCaptions.Count > 0)
            {
                if (dtSource != null)
                {
                    foreach (DataColumn dc in dtSource.Columns)
                    {
                        if (htCaptions.Contains(dc.ColumnName))
                        {
                            dtSource.Columns[dc.ColumnName].ColumnName = htCaptions[dc.ColumnName].ToString();
                            dtSource.AcceptChanges();
                        }
                    }

                }
            }

                    return dtSource;
    }

    private DataTable RemoveColumns(Hashtable htCaption,ref DataTable dtSource)
    {
        DataTable dtResult = new DataTable();
        try
        {
            if(htCaption!=null)
                if (htCaption.Count > 0)
                {
                    if (dtSource != null)
                    {
                        dtResult = dtSource.Copy();
                        //foreach (string keys in htCaption.Keys)
                        foreach(DataColumn dc in dtSource.Columns)
                        {
                            if(!htCaption.ContainsValue(dc.ColumnName))
                            {
                                dtResult.Columns.Remove(dc.ColumnName);
                                dtResult.AcceptChanges();
                            }

                        }

                        dtSource = dtResult.Copy();
                    }
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : RemoveColumns :"+ ex.Message);
        }
        return dtResult;
    }

    


    private DataTable GetBindFields(DataTable dtPgCtr)
    {
        DataTable dtBindFields = new DataTable();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            String strBindRowID = "";
            if(dtPgCtr!=null)
                if (dtPgCtr.Rows.Count > 0)
                {
                    foreach (DataRow dr in dtPgCtr.Rows)
                    {
                        if (dr["control_bind_id"].ToString().Trim() != "")
                        {
                            strBindRowID += "'" + dr["control_bind_id"].ToString() + "',";
                        }
                    }
                    if (strBindRowID.EndsWith(","))
                        strBindRowID = strBindRowID.TrimEnd(',');
                    if (strBindRowID.Trim() != "")
                    {
                        string sql = "select * from sy_bnd where af_row_id in (" + strBindRowID + ")";
                        dtBindFields = Hdd.GetDataTable(sql);
                    }
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetBindFields :"+ ex.Message);
        }
        finally
        {
            Hdd = null;
        }
        return dtBindFields;
    }


    private DataTable getMasterDetail(DataRow drReport)
    {
        DataTable dtRet = new DataTable();
        HDDatabase hdd = new HDDatabase();
        try
        {
            string qry = "select master_obj,display_att,attrib_id,attrib_name from sy_obj_mas_detail ";
            qry += "where object_id=(select af_row_id from sy_obj where object_id='" + drReport["object_id"].ToString() + "')";
            dtRet = hdd.GetDataTable(qry);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getMasterDetail : Error : " + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return dtRet;
    }

    private void AddParameterIcon(ref HtmlTableCell htc, DataRow drWidget, DataRow drSQL,Hashtable htParam)
    {
        try
        {
            if (htParam.Count > 0)
            {
                HtmlTable htable = new HtmlTable();
                htable.Width = "100%";
                htable.CellPadding = 0;
                htable.CellSpacing = 0;
                htable.Border = 0;
                HtmlTableRow hrow = new HtmlTableRow();
                HtmlTableCell hcell = new HtmlTableCell();

                Label imgParameters = new Label();
                imgParameters.Text = "<img src=\"Images/action_24.GIF\" alt=\"Show Parameters\"></img>";
                imgParameters.ToolTip = "Click here for Parameters";
                imgParameters.ID = "img_Param_" + drWidget["af_row_id"].ToString();
                imgParameters.Attributes.Add("onclick", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                imgParameters.CssClass = "controlFont handCursor";
                ////onmouseover
                //hcell.Attributes.Add("onclick", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                //hcell.Attributes.Add("onmouseout", "javascript:HideDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                hcell.Align = "right";
                hcell.Controls.Add(imgParameters);
                hcell.Controls.Add(new LiteralControl("&nbsp;"));
                getHeaderIcons(ref hcell, drWidget); // Added by 'Imran Gani' on 21-Jun-2012, to get the header icons.
                hrow.Controls.Add(hcell);
                htable.Controls.Add(hrow);

                htc.Controls.Add(htable);
                htc.Align = "right";
            }
            else
                getHeaderIcons(ref htc, drWidget); // Added by 'Imran Gani' on 21-Jun-2012, to get the header icons.
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddParameterIcon :" + ex.Message);
        }
    }
    //private void AddParameters(ref HtmlTableCell htc, DataRow drWidget, DataRow drSQL, Hashtable htParam)
    //{
    //    try
    //    {
    //        if (htParam.Count > 0)
    //        {
    //            HtmlTable htable = new HtmlTable();
    //            HtmlTableRow hrow = new HtmlTableRow();
    //            HtmlTableCell hcell = new HtmlTableCell();
    //            //htable.BorderColor = "LightGray";
    //            //htable.CellSpacing = 0;
    //            //htable.CellPadding = 0;
    //            //htable.Border = 1;


    //            hcell = new HtmlTableCell();
    //            hrow = new HtmlTableRow();
    //            Panel pnlParameters = new Panel();
    //            pnlParameters.Width = Unit.Percentage(100);
    //            pnlParameters.ID = "Param_" + drWidget["af_row_id"].ToString();
    //            pnlParameters.Style.Add("display", "none");
    //            pnlParameters.Style.Add(HtmlTextWriterStyle.Position, "absolute");
    //            pnlParameters.Style.Add(HtmlTextWriterStyle.ZIndex, "1");
    //            pnlParameters.EnableViewState = true;
    //            pnlParameters.Attributes.Add("onmouseover", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
    //            pnlParameters.Attributes.Add("onmouseout", "javascript:HideDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
    //            #region Content of the parameter

    //            HtmlTable ht1 = new HtmlTable();
    //            ht1.Width = "100%";
    //            ht1.CellSpacing = 0;
    //            ht1.CellPadding = 0;
    //            ht1.Border = 0;
    //            HtmlTableRow htr1 = new HtmlTableRow();
    //            HtmlTableCell htc1 = new HtmlTableCell();
    //            CreateParameterControls(htParam, ref htc1, drSQL, drWidget);

    //            htr1.Controls.Add(htc1);
    //            ht1.Controls.Add(htr1);
    //            pnlParameters.Controls.Add(ht1);



    //            #endregion
    //            hcell.Controls.Add(pnlParameters);
    //            hrow.Controls.Add(hcell);
    //            htable.Controls.Add(hrow);


    //            htc.Controls.Add(htable);
    //            htc.Align = "right";
    //        }

    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : AddParameters :" + ex.Message);
    //    }
    //}

    private void AddParameters(ref HtmlTableCell htc, DataRow drWidget, DataRow drSQL, Hashtable htParam,HtmlForm frmObj)
    {
        try
        {


            if (htParam.Count > 0)
            {
                HtmlTable htable = new HtmlTable();
                HtmlTableRow hrow = new HtmlTableRow();
                HtmlTableCell hcell = new HtmlTableCell();
                hcell.NoWrap = true;
                htable.Width = "100%";
                htable.BorderColor = "LightGray";
                htable.CellSpacing = 0;
                htable.CellPadding = 0;
                htable.Border = 0;

                //Label imgParameters = new Label();
                //imgParameters.Width = Unit.Percentage(100);
                //imgParameters.Text = "<img src=\"Images/action_24.GIF\" alt=\"Show Parameters\"></img><u>Show Parameters</u>";
                //imgParameters.ID = "img_Param_" + drWidget["af_row_id"].ToString();
                //imgParameters.Attributes.Add("onclick", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                //imgParameters.CssClass = "controlFont";
                ////onclick
                ////hcell.Attributes.Add("onmouseover", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                //////hcell.Attributes.Add("onmouseout", "javascript:HideDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                //hcell.Align = "right"; //left
                //hcell.Controls.Add(imgParameters);
                hrow.Controls.Add(hcell);
                htable.Controls.Add(hrow);


                hcell = new HtmlTableCell();
                hcell.NoWrap = true;
                hrow = new HtmlTableRow();
                Panel pnlParameters = new Panel();
                pnlParameters.ID = "Param_" + drWidget["af_row_id"].ToString();
                pnlParameters.Style.Add("display", "none");
                pnlParameters.Style.Add(HtmlTextWriterStyle.Position, "absolute");
                pnlParameters.Style.Add(HtmlTextWriterStyle.ZIndex, "1");
                pnlParameters.Style.Add("float", "left");
                //pnlParameters.BorderStyle = BorderStyle.Solid;
                pnlParameters.BorderWidth = Unit.Pixel(2);
                pnlParameters.BorderColor = Color.LightGray;

                //pnlParameters.Style.Add("top", "20px");
                //pnlParameters.Style.Add("right", "100px");
                //pnlParameters.Style.Add(HtmlTextWriterStyle.Direction, "rtl");
               
                pnlParameters.EnableViewState = true;
                //onclick
                //pnlParameters.Attributes.Add("onmouseover", "javascript:ShowDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                //pnlParameters.Attributes.Add("onmouseout", "javascript:HideDivForActions('Param_" + drWidget["af_row_id"].ToString() + "');");
                #region Content of the parameter

                HtmlTable ht1 = new HtmlTable();
                ht1.Width = "100%";
                ht1.Border = 0;
                ht1.CellSpacing = 0;
                ht1.CellPadding = 0;
                HtmlTableRow htr1 = new HtmlTableRow();
                HtmlTableCell htc1 = new HtmlTableCell();
                htc1.NoWrap = true;
                CreateParameterControls(htParam, ref htc1, drSQL, drWidget,frmObj);

                htr1.Controls.Add(htc1);
                ht1.Controls.Add(htr1);
                pnlParameters.Controls.Add(ht1);



                #endregion
                //hcell.Align = "Right"; // new 
                //hcell.Style.Add("float", "left");
                hcell.Controls.Add(pnlParameters);

                //CollapsiblePanelExtender CPE = new CollapsiblePanelExtender();
                //CPE.ID = "CPE_"+drWidget["af_row_id"].ToString();
                //CPE.TargetControlID = "Param_" + drWidget["af_row_id"].ToString();
                //CPE.CollapseControlID = "img_Param_"+ drWidget["af_row_id"].ToString();
                //CPE.ExpandControlID = "img_Param_" + drWidget["af_row_id"].ToString();
                //CPE.Enabled = true;
                //CPE.Collapsed = true;
                
                //hcell.Controls.Add(CPE);

                hrow.Controls.Add(hcell);
                htable.Controls.Add(hrow);


                htc.Controls.Add(htable);
                htc.Align = "right"; //left
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddParameters :" + ex.Message);
        }
    }


    private void CreateParameterControls(Hashtable htParam,ref HtmlTableCell htc,DataRow drSQL,DataRow drWidgets,HtmlForm frmObj)
    {
        try
        {
            string sql = drSQL["report_base_sql"].ToString();
            if (sql.Trim() != "")
            {
                //Hashtable htParam = new Hashtable();
                //GetParametersInHashTable(ref htParam, sql,drSQL);
                CreateParameterControls(htParam, ref htc, drWidgets["af_row_id"].ToString(),drSQL,frmObj);
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CreateParameterControls : "+ ex.Message);
        }
    }

    private Hashtable GetParametersInHashTable(ref Hashtable htParam,string sql,DataRow drSQL)
    {
        try
        {
            string param = drSQL["report_base_param"].ToString();
            if (param.Trim() == "")
            {
                if (sql.Contains("$") || sql.Contains("#"))
                {
                    getParameters("$", ref htParam, sql);
                    getParameters("#", ref htParam, sql);
                }
            }
            else
            {
                foreach (string str in param.ToLower().Replace("parameters", "").Split(','))
                {
                    if (str.Trim() == "") continue;
                    if (str.IndexOf("=") == -1)
                        htParam.Add(str.Trim(), getDefaultValue(str.Trim()));
                    else
                        htParam.Add(str.Substring(0, str.IndexOf("=")).Trim(), str.Substring(str.IndexOf("=") + 1).Trim());
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error :GetParametersInHashTable :"+ ex.Message);
        }
        return htParam;
    }

    private Hashtable getParameters(string sChar, ref Hashtable hsParam, string sSql)
    {
        try
        {
            int iPos = 0;
            while (iPos < sSql.Length & iPos != -1)
            {
                string sParam = "";
                iPos = sSql.IndexOf(sChar, iPos);
                if (iPos != -1)
                {
                    int iEndPos = sSql.IndexOf(sChar, iPos + 1);
                    if (iEndPos == -1)
                        iEndPos = sSql.Length - iPos;
                    else
                        iEndPos = iEndPos - (iPos - 1);
                    sParam = sSql.Substring(iPos, iEndPos);
                    sParam = sParam.TrimEnd('\'');
                    if (!hsParam.Contains(sParam))
                        hsParam.Add(sParam, "");
                    iPos = iPos + iEndPos;
                }
            }
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("getParameters : Error : " + Ex.Message);
        }
        return hsParam;
    }

    private string getDefaultValue(string object_field_id)
    {
        string retValue = "''";
        try
        {
            string object_table = object_field_id.Replace("[", "").Substring(0, object_field_id.Replace("[", "").IndexOf("."));
            string field_id = object_field_id.Substring(object_field_id.IndexOf(".") + 1).Replace("]", "");

            HDDatabase hdd = new HDDatabase();
            DataTable dt = hdd.GetDataTable("select control_attrib_type from sy_pg_ctr where control_id='" + field_id + "' and page_id=(select af_row_id from sy_pg where page_table_name='" + object_table + "')");
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "TX")
                    retValue = "''";
                else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DA" || dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DT")
                    retValue = "'" + DateTime.Now.ToShortDateString() + "'";
                else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "BO")
                    retValue = "'false'";
                else
                    retValue = "0";
            }
            dt = null;
            hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getDefaultValue : Error : " + ex.Message);
        }
        return retValue;
    }

    private void CreateParameterControls(Hashtable htParam,ref HtmlTableCell htCell,string af_row_id,DataRow drSQL,HtmlForm frmObj)
    {
        try
        {
            string strParamFields = "";
            if (htParam.Count > 0)
            {
                HtmlTable ht = new HtmlTable();
                ht.Width = "100%";
                ht.Border = 0;
                ht.CellPadding = 0;
                ht.CellSpacing = 0;
                ht.BorderColor = "LightGray";
                //onclick
                //ht.Attributes.Add("onmouseover", "javascript:ShowDivForActions('Param_" + af_row_id + "');");
                ////ht.Attributes.Add("onmouseout", "javascript:HideDivForActions('Param_" + af_row_id + "');");
                HtmlTableRow htr = new HtmlTableRow();
                HtmlTableCell htc = new HtmlTableCell();
                htc.NoWrap = true;
                #region Header
                //htr = new HtmlTableRow();
                //htc = new HtmlTableCell();
                //Label lblheader = new Label();
                //lblheader.Text = "Parameters";
                //lblheader.CssClass = "controlLabelFont";
                ////htc.ColSpan = 2;
                //htc.Attributes.Add("class", "displaygridbottom");
                //htc.Controls.Add(lblheader);
                //htr.Controls.Add(htc);
                //htc = new HtmlTableCell();
                //lblheader = new Label();
                //lblheader.CssClass = "controlLabelFont";
                //lblheader.Text = "Value";
                //htc.Attributes.Add("class", "displaygridbottom");
                //htc.Controls.Add(lblheader);
                //htr.Controls.Add(htc);
                //ht.Controls.Add(htr);
                #endregion

                #region parameters
                //foreach (string str in htParam.Keys)
                //{
                    
                //    htr = new HtmlTableRow();
                //    htr.Attributes.Add("class", "Grid_Row1");
                //    string name = "";
                //    if (str.ToLower().Contains("$"))
                //    {
                //        name = str.Replace("$","");
                //    }
                //    else if(str.ToLower().Contains("#"))
                //    {
                //        name = str.Replace("#","");
                //    }
                //    else if(str.StartsWith("[") && str.EndsWith("]"))
                //    {
                //        name = str.Substring(str.IndexOf(".")+1);
                //        name = name.TrimEnd(']');
                //    }
                //        htc = new HtmlTableCell();
                    
                //        Label lbl = new Label();
                //        lbl.Attributes.Add("class","controlLabelFont");
                //        lbl.Text = name;
                //        htc.Controls.Add(lbl);
                //        htr.Controls.Add(htc);

                //        htc = new HtmlTableCell();
                //        //TextBox txt = new TextBox();
                //        //txt.ID = "p_"+af_row_id+"_"+str;
                //        //txt.Attributes.Add("class","controlFont");
                //        //htc.Controls.Add(txt);

                //        CreateParameters(str, ref htc, af_row_id,htParam); // This will create the control

                //        htr.Controls.Add(htc);
                //        ht.Controls.Add(htr);
                //        strParamFields += str + "|";
                //}
                
                
                
                #endregion  // Commented for testing Jun 15 2010

                #region  Parameter new method

                htc = new HtmlTableCell();
                htr = new HtmlTableRow();
                htc.NoWrap = true;
                HtmlTable htParams = new HtmlTable();
                htParams.Width = "100%";
                htParams.CellPadding = 0;
                htParams.CellSpacing = 0;
                htParams.Border = 0;
                BuildParameters BP = new BuildParameters();
                htParams = BP.createParameters(drSQL["report_base_sql"].ToString(), drSQL["report_base_param"].ToString(), frmObj, af_row_id,true);

                HtmlTableCell htcbutton = new HtmlTableCell();
                HtmlTableRow htrbutton = new HtmlTableRow();
                //htrbutton.Controls.Add(htcbutton);
                htrbutton.Attributes.Add("class", "Grid_Row_actions");
                Button btnOK = new Button();
                btnOK.ID = "btn_" + af_row_id;
                btnOK.Text = "OK";
                btnOK.OnClientClick = "javascript:UpdateEvent();";
                btnOK.UseSubmitBehavior = false;
                btnOK.CausesValidation = false;
                btnOK.Click += new EventHandler(btnOK_Click);
                htcbutton = new HtmlTableCell();
                htcbutton.NoWrap = true;
                htcbutton.ColSpan = 2;
                htcbutton.Controls.Add(btnOK);
                htrbutton.Controls.Add(htcbutton);
                htParams.Controls.Add(htrbutton);

                htc.Controls.Add(htParams);
                htc.ColSpan = 2;
                htr.Controls.Add(htc);
                ht.Controls.Add(htr);
                #endregion


                #region Generate Button
                //htc = new HtmlTableCell();
                //htr = new HtmlTableRow();
                //htr.Attributes.Add("class", "Grid_Row1");
                //htc.ColSpan = 2;
                //Button btnOK = new Button();
                //btnOK.ID = "btn_"+ af_row_id;
                //btnOK.Text = "OK";
                //btnOK.OnClientClick = "javascript:UpdateEvent();";
                //btnOK.UseSubmitBehavior = false;
                //btnOK.CausesValidation = false;
                //btnOK.Click += new EventHandler(btnOK_Click);
                //htc.Controls.Add(btnOK);
                //htr.Controls.Add(htc);

                //#region CreateHidden Fields for Parameters
                //htc = new HtmlTableCell();
                //HiddenField hf = new HiddenField(); //To store Query
                //hf.ID = "hf_sql_"+af_row_id;
                //hf.Value = drSQL["report_base_sql"].ToString();
                //htc.Controls.Add(hf);
                //hf = new HiddenField(); //To store Parameter fields
                //hf.ID = "hf_Param_" + af_row_id;
                //hf.Value = strParamFields;
                //htc.Controls.Add(hf);
                //htr.Controls.Add(htc);
                //#endregion


                //ht.Controls.Add(htr);
                #endregion

                htCell.Controls.Add(ht);
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CreateParameterControls :"+ ex.Message);
        }
    }

    void btnOK_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        
        HtmlForm frmobj = btn.Page.Form;
        if (frmobj != null)
        {
            RefreshDashboards(frmobj);
            #region Old implementation
            //        string strWidgetID = btn.ID.Replace("btn_", "");
    //        string strSQL = "";
    //        string strFields = "";

    //        HiddenField hfSQL = (HiddenField)DDI.FindControl(frmobj.Controls, "hf_sql_" + strWidgetID);
    //        if (hfSQL != null)
    //            strSQL = hfSQL.Value;

    //        HiddenField hfParameters = (HiddenField)DDI.FindControl(frmobj.Controls, "hf_Param_" + strWidgetID);
    //        if (hfParameters != null)
    //            strFields = hfParameters.Value;

    //        Hashtable htParam = new Hashtable();
    //        string[] arrFields = strFields.Split('|');
    //        if (arrFields.Length > 0)
    //        {
    //            for (int i = 0; i < arrFields.Length; i++)
    //            {
    //                if (arrFields[i].ToString().Trim() != "")
    //                    htParam.Add(arrFields[i].ToString(), "");

    //                string controlid = "p_"+strWidgetID+"_"+arrFields[i].ToString();
    //                TextBox txt = (TextBox)DDI.FindControl(frmobj.Controls,controlid);
    //                if (txt != null)
    //                {
    //                    htParam[arrFields[i].ToString()] = txt.Text;
    //                }
    //            }
    //        }

    //        if (htParam.Count > 0)
    //        {
    //            foreach (string str in htParam.Keys)
    //            {
    //                if (strSQL.Contains(str))
    //                    strSQL = strSQL.Replace(str, htParam[str].ToString());
    //            }
    //        }

    //        HDDatabase HDD = new HDDatabase();
            //        DataTable dt = HDD.GetDataTable(strSQL);
            #endregion

        }
        
    }

    private void CreateParameters(string strParam,ref HtmlTableCell htcresult,string af_row_id,Hashtable htParam)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (strParam.Trim() != "")
            {
                string DefaultValue = "";
                if (htParam.Contains(strParam))
                    DefaultValue = htParam[strParam].ToString();

                if(strParam.StartsWith("[") && strParam.EndsWith("]"))
                {
                    if (strParam.Contains("."))
                    {
                        string[] arrparam = strParam.Split('.');
                            string tablename = arrparam[0].ToString().Replace("[","");
                            string attrib_id = arrparam[1].ToString().Replace("]","");

                            if (tablename.Trim() != "" && attrib_id.Trim() != "")
                            {
                                DataTable dt = HDD.GetDataTable("select * from sy_pg_ctr where page_id=(select af_row_id from sy_pg where [page_table_name]='" + tablename + "') and control_attrib_id='" + attrib_id + "'");
                                if (dt.Rows.Count > 0)
                                {
                                    switch (dt.Rows[0]["control_html"].ToString().ToUpper().Trim())
                                    {
                                        case "AN":
                                        case "EM":
                                        case "PW":
                                        case "ENC":
                                        case "TA":
                                        case "TB":
                                            TextBox txtObj = new TextBox();
                                            txtObj.ID = "p_" + af_row_id + "_" + strParam;
                                            txtObj.CssClass = "controlFont";
                                            txtObj.EnableViewState = true;
                                            htcresult.Controls.Add(txtObj);
                                            if (dt.Rows[0]["control_html"].ToString().ToUpper() == "TA")
                                            {
                                                txtObj.TextMode = TextBoxMode.MultiLine;
                                            }
                                            else if (dt.Rows[0]["control_html"].ToString().ToUpper() == "PW")
                                            {
                                                txtObj.TextMode = TextBoxMode.Password;
                                                Literal l = new Literal();
                                                l.Text = "&nbsp;<img src=\"Images/key.gif\" alt=\"Password Field\" border=\"0\" />";
                                                htcresult.Controls.Add(l);
                                            }
                                            if (dt.Rows[0]["control_bind_id"].ToString().Trim() != "")
                                            {
                                                HiddenField hf = new HiddenField();
                                                hf.ID = "hf_p_"+af_row_id+"_"+strParam;
                                                SetValue(hf, hf.ID);
                                                htcresult.Controls.Add(hf);
                                                PageCommonFunctions PCF = new PageCommonFunctions();
                                                PCF.AddSearchLink(ref htcresult, attrib_id, hf.ID, txtObj.ID, dt.Rows[0]["control_bind_id"].ToString());
                                            }

                                            if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DA")
                                                addAjaxCalendarDate(txtObj.ID, ref htcresult);
                                            else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DT")
                                                addAjaxCalendarDateTime(txtObj.ID, ref htcresult);


                                            SetValue(txtObj, txtObj.ID);
                                            break;
                                        case "CB":
                                            CheckBox cbObj = new CheckBox();
                                            cbObj.ID = "p_" + af_row_id + "_" + strParam;
                                            cbObj.CssClass = "controlFont";
                                            htcresult.Controls.Add(cbObj);
                                            SetValue(cbObj, cbObj.ID);
                                            break;
                                        case "DD":
                                        case "DDE":
                                            DropDownList ddlObj = new DropDownList();
                                            ddlObj.ID = "p_"+af_row_id+"_"+strParam;
                                            ddlObj.CssClass = "controlFont";
                                            if (dt.Rows[0]["control_bind_id"].ToString().Trim() != "")
                                            {
                                                DataTable dtBind = new DataTable();
                                                BindControl BC = new BindControl();
                                                BC.Bind(dt.Rows[0]["control_bind_id"].ToString(), ddlObj, ref dtBind, dt.Rows[0]);
                                            }
                                            htcresult.Controls.Add(ddlObj);
                                            SetValue(ddlObj, ddlObj.ID);
                                            break;
                                        case "DT":
                                        case "DA":
                                            TextBox txtDAObj = new TextBox();
                                            txtDAObj.ID = "p_" + af_row_id + "_" + strParam;
                                            txtDAObj.CssClass = "controlFont";
                                            htcresult.Controls.Add(txtDAObj);
                                            if (dt.Rows[0]["control_html"].ToString().ToUpper() == "DA")
                                                addAjaxCalendarDate(txtDAObj.ID, ref htcresult);
                                            else
                                                addAjaxCalendarDateTime(txtDAObj.ID, ref htcresult);
                                            SetValue(txtDAObj, txtDAObj.ID);
                                            break;
                                    }
                                }
                                else
                                {
                                    TextBox txtObj = new TextBox();
                                    txtObj.EnableViewState = true;
                                    txtObj.ID = "p_" + af_row_id + "_" + strParam;
                                    txtObj.Attributes.Add("class", "controlFont");
                                    htcresult.Controls.Add(txtObj);
                                    SetValue(txtObj,txtObj.ID);
                                }
                            }
                    }
                }
                else
                {
                    TextBox txtObj = new TextBox();
                    txtObj.ID = "p_" + af_row_id + "_" + strParam;
                    txtObj.EnableViewState = true;
                    txtObj.Attributes.Add("class", "controlFont");
                    htcresult.Controls.Add(txtObj);
                    SetValue(txtObj, txtObj.ID);
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CreateParameters :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }


    public void GenerateDashboards(ref HtmlTableCell htcresult, ArrayList list, int row, int column, HtmlForm frmObj, DataTable dtWdgSettings)
    {
        HDDatabase HDD = new HDDatabase();
        //Dashboards DB = new Dashboards();
        try
        {
            if (list != null)
                if (list.Count > 0)
                {
                    dashboardColumns = column;
                    if (dtWdgSettings != null) // Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
                        dtWidgetProperty = dtWdgSettings;
                    if (list.Count == 1)
                        this.bWidgetPage = true;
                    int ilist = list.Count;
                    int cnt = 1;
                    HtmlTable ht = new HtmlTable();
                    ht.Width = "100%";
                    ht.CellPadding = 0;
                    ht.CellSpacing = 5;
                    ht.Border = 0;
                    HtmlTableRow htr = new HtmlTableRow();
                    HtmlTableCell htc = new HtmlTableCell();

                    for (int i = 0; i < row; i++)
                    {
                        htr = new HtmlTableRow();

                        for (int j = 0; j < column; j++)
                        {
                            htc = new HtmlTableCell();
                            if (cnt <= ilist)
                            {
                                //htc.VAlign = "top";
                                //string strDBafrowid = list[cnt - 1].ToString();
                                //GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                //cnt += 1;

                                #region Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
                                htc.VAlign = "top";
                                string strDBafrowid = list[cnt - 1].ToString();
                                if (dtWdgSettings != null && dtWdgSettings.Rows.Count > 0)
                                {
                                    DataRow[] dr = dtWdgSettings.Select("widget = '" + strDBafrowid + "'");
                                    if (dr.Length > 0)
                                    {
                                        if (dr[0]["fullview"].ToString().ToLower() == "true")
                                        {
                                            if (j == 0)
                                            {
                                                GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                                htc.ColSpan = column;
                                                htr.Controls.Add(htc);
                                                cnt += 1;
                                                break;
                                            }
                                        }
                                        else if (dr[0]["newsection"].ToString().ToLower() == "true")
                                        {
                                            if (j == 0)
                                            {
                                                if (dr[0]["widget_size"].ToString().ToLower() == "small")  // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Small widget
                                                    htc.Controls.Add(getSmallwidget(strDBafrowid, ref cnt, list, dtWdgSettings, frmObj));
                                                else
                                                {
                                                    GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                                    cnt += 1;
                                                }
                                            }
                                        }
                                        else if (dr[0]["widget_size"].ToString().ToLower() == "small") // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Small widget
                                            htc.Controls.Add(getSmallwidget(strDBafrowid, ref cnt, list, dtWdgSettings, frmObj));
                                        else
                                        {
                                            GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                            cnt += 1;
                                        }
                                    }
                                    else
                                    {
                                        GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                        cnt += 1;
                                    }
                                }
                                else
                                {
                                    GenerateWidgets(strDBafrowid, ref htc, true, frmObj, true);
                                    cnt += 1;
                                }
                                #endregion
                            }
                            htr.Controls.Add(htc);
                        }
                        ht.Controls.Add(htr);
                    }

                    htcresult.Controls.Add(ht);
                }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GenerateDashboards :" + ex.Message);
        }
        finally
        {
            HDD = null;
            //DB = null;
        }
    }


    private void GetValuesofParameters(string strwidgetaf_row_id,ref Hashtable htParam,HtmlForm frmObj,DataSet dsPageControls)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            if (frmObj != null)
            {
                Hashtable httemp = new Hashtable();
                foreach (string str in htParam.Keys)
                {

                    if (str.StartsWith("[") && str.EndsWith("]"))
                    {
                        string[] arrstr = str.Replace("[", "").Replace("]", "").Split('.');
                        if (arrstr.Length > 0)
                        {
                            string control_id = "p_" + strwidgetaf_row_id + "_" + str;
                            string value = "";
                            if (dsPageControls.Tables.Count > 0)
                            {
                                if (dsPageControls.Tables[arrstr[0]] != null)
                                {
                                    DataRow[] drPgCtr = dsPageControls.Tables[arrstr[0]].Select("control_attrib_id = '"+arrstr[1]+"'");
                                    if (drPgCtr[0]["control_bind_id"].ToString().Trim() != "")
                                        if (drPgCtr[0]["control_html"].ToString().ToUpper() == "TB")
                                            control_id = "p_" + strwidgetaf_row_id + "_" + str;
                                    
                                    value = GetValueFromControl(control_id,frmObj,drPgCtr[0]);
                                    httemp.Add(str,value);
                                }
                                else
                                {
                                    value = GetValueFromControl(control_id, frmObj,null);
                                    httemp.Add(str, value);
                                }
                            }
                            else
                            {
                                value = GetValueFromControl(control_id, frmObj,null);
                                httemp.Add(str, value);
                            }
                        }
                    }
                    else
                    {
                        string control_id = "p_" + strwidgetaf_row_id + "_" + str;
                        string value = GetValueFromControl(control_id,frmObj,null);
                        httemp.Add(str,value);
                    }

                }

                if(httemp.Count>0)
                    htParam = httemp;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetValuesofParameters :" + ex.Message);
        }
        finally
        {
            DDI = null;
        }

    }

    private string GetValueFromControl(string id, HtmlForm frmObj,DataRow drPgCtrl)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        HDDatabase HDD = new HDDatabase();
        string result = "";
        try
        {
            Control con = DDI.FindControl(frmObj.Controls, id);
            if (con != null)
            {
                string strBindRowID = "";
                string controlhtml = "";
                if (drPgCtrl != null)
                {
                    strBindRowID = drPgCtrl["control_bind_id"].ToString();
                    controlhtml = drPgCtrl["control_html"].ToString();
                }


                if (con is TextBox)
                {
                    TextBox txtObj = (TextBox)con;
                    result = txtObj.Text;
                    if(strBindRowID.Trim()!="")
                    {
                        string textvalue = "";
                        string hfvalue = "";
                        Control hcon = DDI.FindControl(frmObj.Controls, "hf_" + id);
                        if (hcon != null)
                        {
                            HiddenField hf = (HiddenField)hcon;
                            hfvalue = hf.Value;
                            textvalue = txtObj.Text;
                            BindControl BC = new BindControl();
                            string sql = BC.GetBindSql(strBindRowID);
                            DataTable dt = HDD.GetDataTable(sql);
                            if (dt != null)
                            {
                                DataRow[] drselect = dt.Select("val='" + hfvalue + "' and fld='" + textvalue + "'");
                                if (drselect.Length > 0)
                                {
                                    txtObj.Text = drselect[0]["Fld"].ToString();
                                    hf.Value = drselect[0]["val"].ToString();
                                    result = hf.Value;
                                }
                                else
                                {
                                    drselect = dt.Select("Fld='" + textvalue + "'");
                                    if (drselect.Length > 0)
                                    {
                                        txtObj.Text = drselect[0]["fld"].ToString();
                                        hf.Value = drselect[0]["val"].ToString();
                                        result = hf.Value;
                                    }
                                    else
                                    {
                                        result = hf.Value;
                                    }
                                }
                            }
                            else
                                result = hf.Value;
                        }
                    }
                    
                }
                else if (con is CheckBox)
                {
                    CheckBox cbObj = (CheckBox)con;
                    result = cbObj.Checked.ToString();
                }
                else if (con is HiddenField)
                {
                    HiddenField hf = (HiddenField)con;
                    result = hf.Value;
                }
                else if (con is DropDownList)
                {
                    DropDownList ddlObj = (DropDownList)con;
                    result = ddlObj.SelectedValue;
                }
            }
            else if (HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id] != null)
            {
                result = HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id].ToString();
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetValueFromControl : "+ ex.Message);
        }
        finally
        {
            DDI = null;
            HDD = null;
        }
        return result;
    }
    private string applyafadminsecurity(string sql)
    {

        try
        {
            if (HttpContext.Current.Session["roleid"].ToString() != "e7029dafbe379f85")
            {


                SecurityFilter objSec = new SecurityFilter();
                string sAFAdmin = objSec.QueryForAFAdmin();
                //string sCustodianFilter = objSec.QueryForCustodianFilter();
                //if (sCustodianFilter.Trim() != "")
                //if (!sCustodianFilter.StartsWith("or"))
                // {
                //sAFAdmin += " and " + sCustodianFilter;
                // }
                // else
                // {
                //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                //{
                //   sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                //sAFAdmin += " " + sCustodianFilter;
                // }
                //}

                if (sql.Contains("order by"))
                {
                    if (sAFAdmin.Trim() != "")
                    {
                        sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
                    }
                }
                else
                {
                    if (sAFAdmin.Trim() != "")
                    {
                        if (sql.Contains("where "))
                        {
                            sql = sql + " and " + sAFAdmin;
                        }
                        else
                        {
                            sql = sql + " where " + sAFAdmin;
                        }
                    }
                }
            }


        }
        catch
        {

        }
        return sql;
    }

    private void addAjaxCalendarDate(string id, ref HtmlTableCell htc)
    {
        if (id.Length < 1) return;
        CalendarExtender ce = new CalendarExtender();
        ce.ID = "ce_ajax_" + id;
        //ce.Format = getUserDateFormat(); // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        ce.Format = MBLocalization.getDateFormat(HttpContext.Current.Session["userlocale"].ToString()); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
        ce.TargetControlID = id;
        htc.Controls.Add(ce);
    }

    private void addAjaxCalendarDateTime(string id, ref HtmlTableCell htc)
    {
        if (id.Length < 1) return;
        CalendarExtender ce = new CalendarExtender();
        ce.ID = "ce_ajax_" + id;
        //ce.Format = getUserDateFormat() + " hh:mm tt"; // Commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
        ce.Format = MBLocalization.getDateTimeFormat(HttpContext.Current.Session["userlocale"].ToString()); // Added by 'Imran Gani' on 28-Feb-2014, for MBLocale
        ce.TargetControlID = id;
        htc.Controls.Add(ce);
    }

    #region Old code commented by 'Imran Gani' on 28-Feb-2014, for MBLocale
    //private string getUserDateFormat()
    //{
    //    Localization ll = new Localization();
    //    string ret = ll.getDateFormat();
    //    ll = null;
    //    return ret;
    //}
    #endregion

    private void RefreshDashboards(HtmlForm frmObj,bool bReRender)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("widgetdesigner.aspx"))
            {
                if(HttpContext.Current.Request.QueryString["PK"]!=null)
                {
                    Control con = DDI.FindControl(frmObj.Controls,"tdPreview");
                    if(con!=null)
                    {
                        HtmlTableCell htc = (HtmlTableCell)con;

                        HtmlTable httemp = new HtmlTable();
                        httemp.CellPadding = 0;
                        httemp.CellSpacing = 0;
                        httemp.Border = 0;
                        httemp.Width = "100%";
                        HtmlTableRow htrtemp = new HtmlTableRow();
                        HtmlTableCell htctemp = new HtmlTableCell();

                        GenerateWidgets(HttpContext.Current.Request.QueryString["PK"].ToString(), ref htctemp, true, frmObj,false);
                        
                        htc.Controls.Clear();

                        htrtemp.Controls.Add(htctemp);
                        httemp.Controls.Add(htrtemp);
                        htc.Controls.Add(httemp);
                    }
                }
            }
            else if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("dashboarddesigner.aspx"))
            {
                int itemcount = 0;
                int colcount = 0;
                int rowcount = 0;
                ArrayList arrlist = new ArrayList();
                Control con = DDI.FindControl(frmObj.Controls, "lstSelectedDashboards");
                if (con != null)
                {
                    ListBox list = (ListBox)con;
                    itemcount = list.Items.Count;
                    foreach (ListItem item in list.Items)
                    {
                        arrlist.Add(item.Value);
                    }

                    con = DDI.FindControl(frmObj.Controls, "ddlLayoutStyle");
                    if (con != null)
                    {
                        DropDownList ddl = (DropDownList)con;
                        colcount = Convert.ToInt32(ddl.SelectedValue);
                    }

                    #region Added by 'Imran Gani' on 07-Aug-2014, for Dashboard widget property
                    DataTable dtWdgSettings = new DataTable();
                    int WdgSettingsCount = 0;
                    con = DDI.FindControl(frmObj.Controls, "hfJsonWdgSettings");
                    if (con != null)
                    {
                        HiddenField hfJsonWdgSettings = (HiddenField)con;
                        dtWdgSettings = JsonFunctions.JsonFunctions.JsonToDataTable(hfJsonWdgSettings.Value);
                        if (dtWdgSettings != null && dtWdgSettings.Rows.Count > 0)
                            WdgSettingsCount = dtWdgSettings.Select("fullview = 'true' or newsection = 'true'").Length;
                    }

                    itemcount = itemcount - WdgSettingsCount;
                    rowcount = GetRowCount(itemcount, colcount) + WdgSettingsCount;
                    #endregion

                    con = DDI.FindControl(frmObj.Controls,"td_dashboard");
                    if(con!=null)
                    {
                        HtmlTableCell htc = (HtmlTableCell)con;

                        HtmlTable httemp = new HtmlTable();
                        HtmlTableRow htrtemp = new HtmlTableRow();
                        HtmlTableCell htctemp = new HtmlTableCell();

                        GenerateDashboards(ref htctemp, arrlist, rowcount, colcount, frmObj, dtWdgSettings);

                        htc.Controls.Clear();

                        htrtemp.Controls.Add(htctemp);
                        httemp.Controls.Add(htrtemp);
                        htc.Controls.Add(httemp);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RefreshDashboards :" + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private int GetRowCount(int ItemCount, int ColCount)
    {
        int rowcount = 0;
        try
        {
            if (ItemCount > 0)
            {
                //decimal dec = ItemCount / ColCount;
                double drow = ItemCount / ColCount;
                int inttemp = Convert.ToInt32(drow);
                if (inttemp == 0)
                    inttemp = 1;
                int temp = ItemCount % ColCount;
                if (temp > 0)
                    rowcount = inttemp + 1;
                else
                    rowcount = inttemp;
                if (ItemCount <= ColCount)  //Add only Single Row
                    rowcount = 1;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetRowCount :" + ex.Message);
        }
        return rowcount;
    }

    private void SetValue(object obj, string id)
    {
        try
        {
            string value = "";
                if (obj is TextBox)
                {
                    if (HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id] != null)
                    {
                        value = HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id].ToString();
                    }
                    TextBox txt = (TextBox)obj;
                    txt.Text = value;
                }
                else if (obj is CheckBox)
                {
                    CheckBox cb = (CheckBox)obj;
                    if (HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id] != null)
                    {
                        value = HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id].ToString();
                    }
                    if (value.Trim().ToLower() == "on")
                        value = "true";
                    else
                        value = "false";
                    cb.Checked = value.Trim() != "" ? Convert.ToBoolean(value) : false;
                }
                else if (obj is DropDownList)
                {
                    DropDownList ddl = (DropDownList)obj;
                    if (HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id] != null)
                    {
                        value = HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id].ToString();
                    }
                    ListItem item = ddl.Items.FindByText(value);
                    ddl.Items[ddl.Items.IndexOf(item)].Selected = true;
                    
                }
                else if (obj is HiddenField)
                {
                    HiddenField hf = (HiddenField)obj;
                    if (HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id] != null)
                    {
                        value = HttpContext.Current.Request.Form["ctl00$ContentPlaceHolder3$" + id].ToString();
                    }
                    hf.Value = value;
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : SetValue : "+ ex.Message);
        }
    }

    
    private void GetPageControls(Hashtable htParam, ref DataSet dsPageControls)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (htParam.Count > 0)
            {
                string tablenames = "";
                foreach (string str in htParam.Keys)
                {
                    if(str.StartsWith("[") && str.EndsWith("]"))
                    {
                        string[] arrstr = str.Replace("[","").Replace("]","").Split('.');
                        if (!tablenames.Contains(arrstr[0]))
                            tablenames += arrstr[0] +"|";
                    }
                }

                if (tablenames.Trim() != "")
                {
                    string[] arrtable = tablenames.Split('|');
                    for (int i = 0; i < arrtable.Length; i++)
                    {
                        string attrib_id = "";
                        if (arrtable[i].Trim() != "")
                        {
                            foreach (string str in htParam.Keys)
                            {
                                if (str.Contains(arrtable[i]))
                                {
                                    string[] arrkey = str.Replace("[","").Replace("]","").Split('.');
                                    if (!attrib_id.Contains(arrkey[1].ToString()))
                                        attrib_id += "'" + arrkey[1].ToString() + "',";
                                }
                            }

                            if (attrib_id.Trim() != "")
                            {
                                if (attrib_id.EndsWith(","))
                                {
                                    attrib_id = attrib_id.TrimEnd(',');
                                }
                                DataTable dt = HDD.GetDataTable("select * From sy_pg_ctr where page_id = (select top 1 af_row_id from sy_pg where page_table_name = '" + arrtable[i].ToString() + "') and control_attrib_id in ("+attrib_id+")",arrtable[i]);
                                if (dt != null)
                                    dsPageControls.Tables.Add(dt.Copy());
                            }
                            
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetPageControls : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }
    #region unused
    //private void SetPopUpFocus(ref Control con)
    //{
    //    try
    //    {
    //        if (con != null)
    //        {
    //            if (con.Controls.Count > 0)
    //            {
    //                foreach (Control ctrl in con.Controls)
    //                {
    //                    SetPopUpFocus(ref ctrl);
    //                }
    //            }
    //            else
    //            {

    //            }
    //        }
    //    }
    //    catch(Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : SetPopupFocus : "+ ex.Message);
    //    }
    //}
    #endregion

    private Color[] ColorPalette()
    {
        Color[] colorlist = {Color.AliceBlue,Color.BurlyWood,Color.Cyan,Color.DarkOrange,Color.DarkSeaGreen,Color.DeepPink,Color.DodgerBlue,Color.FloralWhite,Color.Gold,Color.Honeydew,Color.Lavender,Color.LemonChiffon,Color.LightSalmon,Color.Maroon,Color.Olive,Color.OrangeRed,Color.SteelBlue,Color.Tomato,Color.Wheat,Color.YellowGreen,Color.BurlyWood };
        return colorlist;
    }

    private PaintElement[] CustomPaintElements()
    {
        #region Old color
       // PaintElement[] paintelement = { 
            //new PaintElement(Color.Red), 
            //new PaintElement(Color.Blue),
            ////new PaintElement(Color.AliceBlue),
            //new PaintElement(Color.BurlyWood),
            ////new PaintElement(Color.Cyan),
            //new PaintElement(Color.DarkOrange),
            //new PaintElement(Color.DarkSeaGreen),
            //new PaintElement(Color.DeepPink),
            //new PaintElement(Color.DodgerBlue),
            //new PaintElement(Color.FloralWhite),
            //new PaintElement(Color.Gold),
            //new PaintElement(Color.Honeydew),
            //new PaintElement(Color.Lavender),
            //new PaintElement(Color.LemonChiffon),
            //new PaintElement(Color.LightSalmon),
            //new PaintElement(Color.Maroon),
            //new PaintElement(Color.Olive),
            //new PaintElement(Color.OrangeRed),
            //new PaintElement(Color.SteelBlue),
            //new PaintElement(Color.Tomato),
            //new PaintElement(Color.Wheat),
            //new PaintElement(Color.YellowGreen),
            //new PaintElement(Color.BurlyWood),
            //new PaintElement(Color.RoyalBlue)
            //                          };
        #endregion
        PaintElement[] paintelement = { 
            new PaintElement(Color.Red), 
            new PaintElement(Color.Blue),
            new PaintElement(Color.BurlyWood),
            new PaintElement(Color.Lavender),
            new PaintElement(Color.DarkSeaGreen),
            new PaintElement(Color.LightPink),
            new PaintElement(Color.Gold),
            new PaintElement(Color.DarkSalmon),
            new PaintElement(Color.LavenderBlush),
            new PaintElement(Color.LemonChiffon),
            new PaintElement(Color.Honeydew),
            new PaintElement(Color.Olive),
            new PaintElement(Color.SteelBlue),
            new PaintElement(Color.LightSalmon),
            new PaintElement(Color.Maroon),
            new PaintElement(Color.OrangeRed),
            new PaintElement(Color.YellowGreen),
            new PaintElement(Color.Tomato),
            new PaintElement(Color.Wheat),
            new PaintElement(Color.RoyalBlue),
            new PaintElement(Color.DarkOrange),
                                      };
        return paintelement;
    }

    private void UpdateWidgets(string strWidgetID,HtmlForm frmObj)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        DataTable dt = new DataTable();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string strControlid = "wgt_" + strWidgetID;
            Control con = DDI.FindControl(frmObj.Controls, strControlid);
            if (con != null)
            {
                string sql = "select * from sy_widgets where af_row_id = '" + strWidgetID + "'";
                dt = HDD.GetDataTable(sql);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        DataTable dtInput = new DataTable();
                        string strSQL = "";
                        ArrayList arrXAxis = new ArrayList();
                        ArrayList arrYAxis = new ArrayList();
                        GetWidgetData(dr, ref strSQL, ref dtInput, frmObj, ref arrXAxis, ref arrYAxis);
                        //SetWidgetSource(dtInput, con, arrXAxis, arrYAxis, dr);
                        SetWidgetSourceForMSChart(dtInput, con, arrXAxis, arrYAxis, dr); // Added by 'Imran Gani' on 19-Nov-2012, to display the parameter widgets.

                        // Below lines are added by 'Imran Gani' on 28-Jun-2012, to display the widgets report in a data grid view.
                        string sCurrentUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
                        if (sCurrentUrl.Contains("WidgetsView.aspx?"))
                        {
                            HandleDataType4GridTable(dtInput, dr); // Added by 'Imran Gani' on 06-Mar-2014, for MBLocale
                            DisplayDataGrid(dtInput, ref frmObj);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateWidgets :" + ex.Message);
        }
        finally
        {
            DDI = null;
            HDD = null;
        }
    }

    /// <summary>
    /// To display the widgets report in a data grid view.
    /// </summary>
    /// <param name="dtInput">Input data table.</param>
    /// <param name="frmObj">Page Form.</param>
    private void DisplayDataGrid(DataTable dtInput, ref HtmlForm frmObj) // Added by 'Imran Gani' on 28-Jun-2012, to display the widgets report in a data grid view.
    {
        try
        {
            if (dtInput != null && dtInput.Rows.Count > 0)
            {
                if (dtInput.Columns.Contains("af_row_id"))
                {
                    dtInput.Columns.Remove("af_row_id");
                }
                Label lblMsg = (Label)frmObj.FindControl("lblNoDataMsg");
                lblMsg.Text = "";
                GridView gv = (GridView)frmObj.FindControl("wgt_GridView");
                gv.DataSource = dtInput;
                gv.DataBind();
                gv.Visible = true;
            }
            else
            {
                GridView gv = (GridView)frmObj.FindControl("wgt_GridView");
                gv.Visible = false;
                Label lblMsg = (Label)frmObj.FindControl("lblNoDataMsg");
                lblMsg.Text = "Data not available";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : DisplayDataGrid :" + ex.Message);
        }
        finally
        {
        }
    }

    private void RefreshDashboards(HtmlForm frmObj)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("widgetdesigner.aspx") || HttpContext.Current.Request.Url.ToString().ToLower().Contains("widgetsview.aspx")) // Modified by 'Imran Gani' on 27-Jun-2012, for parameterized widgets in Widgets View.
            {
                if (HttpContext.Current.Request.QueryString["PK"] != null)
                {
                    UpdateWidgets(HttpContext.Current.Request.QueryString["PK"].ToString(),frmObj);
                }
            }
            else if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("dashboarddesigner.aspx"))
            {
                int itemcount = 0;
                int colcount = 0;
                int rowcount = 0;
                ArrayList arrlist = new ArrayList();
                Control con = DDI.FindControl(frmObj.Controls, "lstSelectedDashboards");
                if (con != null)
                {
                    ListBox list = (ListBox)con;
                    itemcount = list.Items.Count;
                    foreach (ListItem item in list.Items)
                    {
                        arrlist.Add(item.Value);
                    }

                    con = DDI.FindControl(frmObj.Controls, "ddlLayoutStyle");
                    if (con != null)
                    {
                        DropDownList ddl = (DropDownList)con;
                        colcount = Convert.ToInt32(ddl.SelectedValue);
                    }

                    rowcount = GetRowCount(itemcount, colcount);

                    con = DDI.FindControl(frmObj.Controls, "td_dashboard");
                    if (con != null)
                    {

                        //GenerateDashboards(ref htctemp, arrlist, rowcount, colcount, frmObj);

                        for (int i = 0; i < arrlist.Count; i++)
                        {
                            UpdateWidgets(arrlist[i].ToString(), frmObj);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RefreshDashboards :" + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private void ApplyGridSettingsNew(ref Infragistics.WebUI.UltraWebGrid.UltraWebGrid objGrid, DataRow drWidget)
    {
        try
        {
            if (objGrid != null)
            {
                if (drWidget != null)
                    objGrid.ID = "wgt_" + drWidget["af_row_id"].ToString();

                //UltraGridBand gridband = new UltraGridBand();
                //gridband.AddNew();
                //objGrid.Bands..Add(gridband);


                objGrid.DisplayLayout.AllowColSizingDefault = AllowSizing.Free;
                objGrid.DisplayLayout.BorderCollapseDefault = BorderCollapse.Separate;
                objGrid.DisplayLayout.RowHeightDefault = Unit.Pixel(20);
                objGrid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;
                objGrid.DisplayLayout.SelectTypeRowDefault = SelectType.Extended;
                objGrid.DisplayLayout.StationaryMarginsOutlookGroupBy = true;
                objGrid.DisplayLayout.ViewType = ViewType.Hierarchical;
                objGrid.DisplayLayout.RowSizingDefault = AllowSizing.Free;
                objGrid.DisplayLayout.TableLayout = TableLayout.Fixed;
                objGrid.DisplayLayout.AllowDeleteDefault = AllowDelete.No;


                objGrid.DisplayLayout.GroupByBox.BoxStyle.BackColor = Color.FromName("ActiveBorder");
                objGrid.DisplayLayout.GroupByBox.BoxStyle.BorderColor = Color.FromName("Window");

                objGrid.DisplayLayout.GroupByRowStyleDefault.BackColor = Color.FromName("Control");
                objGrid.DisplayLayout.GroupByRowStyleDefault.BorderColor = Color.FromName("Window");

                objGrid.DisplayLayout.FooterStyleDefault.BackColor = Color.FromName("LightGray");
                objGrid.DisplayLayout.FooterStyleDefault.BorderStyle = BorderStyle.Solid;
                objGrid.DisplayLayout.FooterStyleDefault.BorderWidth = Unit.Pixel(1);
                objGrid.DisplayLayout.FooterStyleDefault.BorderDetails.ColorLeft = Color.White;
                objGrid.DisplayLayout.FooterStyleDefault.BorderDetails.ColorTop = Color.White;
                objGrid.DisplayLayout.FooterStyleDefault.BorderDetails.WidthLeft = Unit.Pixel(1);
                objGrid.DisplayLayout.FooterStyleDefault.BorderDetails.WidthTop = Unit.Pixel(1);
                objGrid.DisplayLayout.RowStyleDefault.BackColor = Color.FromName("Window");
                objGrid.DisplayLayout.RowStyleDefault.BorderColor = Color.Silver;
                objGrid.DisplayLayout.RowStyleDefault.BorderStyle = BorderStyle.Solid;
                objGrid.DisplayLayout.RowStyleDefault.BorderWidth = Unit.Pixel(1);
                objGrid.DisplayLayout.RowStyleDefault.Font.Names = new string[] {"Microsoft Sans Serif"};
                objGrid.DisplayLayout.RowStyleDefault.Font.Size = FontUnit.Point(8);
                 objGrid.DisplayLayout.RowStyleDefault.BorderDetails.ColorLeft = Color.FromName("Window");               
                objGrid.DisplayLayout.RowStyleDefault.BorderDetails.ColorTop = Color.FromName("White");
                 objGrid.DisplayLayout.RowStyleDefault.Padding.Left = Unit.Pixel(3);

                objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.BackColor = Color.White;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.BorderColor = Color.Silver;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.BorderStyle = BorderStyle.Solid;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.BorderWidth = Unit.Pixel(1);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.CustomRules = "overflow:auto";
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.Font.Names = new string[] {"Verdana","Arial","Helvetica","sans-serif"};
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.Font.Size = FontUnit.Point(11);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterOperandDropDownStyle.Padding.Left = Unit.Pixel(2);
                 
                objGrid.DisplayLayout.FilterOptionsDefault.FilterHighlightRowStyle.BackColor = Color.FromName("#151C55");
                objGrid.DisplayLayout.FilterOptionsDefault.FilterHighlightRowStyle.ForeColor = Color.White;

                objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.BackColor = Color.White;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.BorderColor = Color.Silver;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.BorderStyle = BorderStyle.Solid;
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.BorderWidth = Unit.Pixel(1);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.CustomRules = "overflow:auto";
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.Font.Names = new string[] {"Verdana","Arial","Helvetica","sans-serif"};
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.Font.Size = FontUnit.Point(11);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.Height = Unit.Pixel(300);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.Width = Unit.Pixel(200);
                    objGrid.DisplayLayout.FilterOptionsDefault.FilterDropDownStyle.Padding.Left = Unit.Pixel(2);

                objGrid.DisplayLayout.HeaderStyleDefault.BackColor = Color.LightGray;
                objGrid.DisplayLayout.HeaderStyleDefault.BorderStyle = BorderStyle.Solid;
                objGrid.DisplayLayout.HeaderStyleDefault.HorizontalAlign = HorizontalAlign.Left;
                objGrid.DisplayLayout.HeaderStyleDefault.BorderDetails.ColorLeft = Color.White;
                objGrid.DisplayLayout.HeaderStyleDefault.BorderDetails.ColorTop = Color.White;
                objGrid.DisplayLayout.HeaderStyleDefault.BorderDetails.WidthLeft = Unit.Pixel(1);
                objGrid.DisplayLayout.HeaderStyleDefault.BorderDetails.WidthTop = Unit.Pixel(1);

                objGrid.DisplayLayout.EditCellStyleDefault.BorderStyle = BorderStyle.None;
                objGrid.DisplayLayout.EditCellStyleDefault.BorderWidth = Unit.Pixel(0);

                objGrid.DisplayLayout.FrameStyle.BackColor = Color.FromName("Window");
                objGrid.DisplayLayout.FrameStyle.BorderColor = Color.LightGray;
                objGrid.DisplayLayout.FrameStyle.Font.Size = FontUnit.Point(8);
                objGrid.DisplayLayout.FrameStyle.Height = Unit.Pixel(260);
                objGrid.DisplayLayout.FrameStyle.Width = Unit.Pixel(230);

                objGrid.DisplayLayout.Pager.MinimumPagesForDisplay = 2;
                objGrid.DisplayLayout.Pager.PagerStyle.BackColor = Color.LightGray;
                objGrid.DisplayLayout.Pager.PagerStyle.BorderStyle = BorderStyle.Solid;
                objGrid.DisplayLayout.Pager.PagerStyle.BorderWidth = Unit.Pixel(1);
                objGrid.DisplayLayout.Pager.PagerStyle.BorderDetails.ColorTop = Color.White;
                objGrid.DisplayLayout.Pager.PagerStyle.BorderDetails.ColorLeft = Color.White;
                objGrid.DisplayLayout.Pager.PagerStyle.BorderDetails.WidthTop = Unit.Pixel(1);
                objGrid.DisplayLayout.Pager.PagerStyle.BorderDetails.WidthLeft = Unit.Pixel(1);
                 
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BackColor = Color.FromName("Window");
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderColor = Color.FromName("InactiveCaption");
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderStyle = BorderStyle.Solid;
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderWidth = Unit.Pixel(1);
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderDetails.ColorLeft= Color.White;
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderDetails.ColorTop= Color.White;
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderDetails.WidthLeft = Unit.Pixel(1);
                objGrid.DisplayLayout.AddNewBox.BoxStyle.BorderDetails.WidthTop = Unit.Pixel(1);



                //objGrid.Width = Unit.Pixel(800);
                objGrid.GridLines = UltraGridLines.Both;
                objGrid.CellPadding = 0;
                objGrid.CellSpacing = 0;


                //string strRowColor = getCSSPropertyValue("Grid_Row1", "background-color");
                
                //objGrid.DisplayLayout.HeaderStyleDefault.BackColor = System.Drawing.Color.FromName(strHeaderColor);
                //objGrid.DisplayLayout.HeaderStyleDefault.CssClass = "controlLabelFont";
                //objGrid.DisplayLayout.RowStyleDefault.CssClass = "controlFont";
                //objGrid.DisplayLayout.RowAlternateStyleDefault.BackColor = System.Drawing.Color.FromName(strRowColor);

                objGrid.DisplayLayout.ScrollBarView = ScrollBarView.Both;
                //objGrid.DisplayLayout.ScrollBar = ScrollBar.Auto;

                objGrid.DisplayLayout.RowSelectorsDefault = RowSelectors.No;






                
                
                
                
                
                
                
                
                objGrid.DisplayLayout.NoDataMessage = "No Data Available";
                objGrid.DisplayLayout.Grid.Width = Unit.Percentage(100);
                //objGrid.DisplayLayout.Grid.Height = Unit.Pixel(300);
                objGrid.DisplayLayout.Grid.BorderColor = System.Drawing.Color.LightGray;
                objGrid.DisplayLayout.Grid.CellPadding = 1;
                objGrid.DisplayLayout.Grid.CellSpacing = 1;


                objGrid.Load += new EventHandler(objGrid_Load);

                //objGrid.DisplayLayout.Grid.Rows.Band.RowStyle.CssClass = "controlFont";
                objGrid.DisplayLayout.AllowSortingDefault = AllowSorting.OnClient;

                
                //objGrid.DisplayLayout.RowStyleDefault.TextOverflow = TextOverflow.Ellipsis;
                objGrid.DisplayLayout.RowStyleDefault.CssClass = "controlFont";
                objGrid.DisplayLayout.RowAlternateStyleDefault.CssClass = "Grid_Row1";
                objGrid.DisplayLayout.Rows.Band.RowStyle.CssClass = "controlFont";

                objGrid.DisplayLayout.HeaderStyleDefault.CssClass = "Grid_Header";

                string strHeaderColor = getCSSPropertyValue("Grid_Header", "background-color");
                objGrid.DisplayLayout.HeaderStyleDefault.BackColor = Color.FromName(strHeaderColor);

            }
        }
        catch
        {
        }
    }
    #region Ordinates
    public void GetWidgetQuery(string strSourceType, string strSource, ref string strWidgetSQL, ref DataTable dtWidgetData, HtmlForm frmObj,ref Hashtable htColumns)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (strSource.Trim() != "" && strSourceType.Trim() != "")
            {
                string sql = "";
                DataTable dt = new DataTable();
                DataSet dsPageControls = new DataSet();

                switch (strSourceType.ToLower())
                {
                    case "query":
                        sql = "select * from sy_report_sql where af_row_id = '" + strSource + "'";
                        dt = HDD.GetDataTable(sql);
                        if (dt != null)
                            if (dt.Rows.Count > 0)
                            {
                                //decode added by Sampath on 27-Apr-2012
                                //CommonFunctions.decodeData(dt);
                                strWidgetSQL = dt.Rows[0]["report_base_sql"].ToString();

                                Hashtable htParam = new Hashtable();
                                BuildParameters BP = new BuildParameters();
                                //htParam = BP.updateParameters(strWidgetSQL, dt.Rows[0]["report_base_param"].ToString(), frmObj, ""); //dr["af_row_id"].ToString()
                                BP.GetParametersInHashTable(strWidgetSQL, dt.Rows[0]["report_base_param"].ToString(), ref htParam);
                                strWidgetSQL = BP.makeSQL(htParam, strWidgetSQL);
                                dtWidgetData = HDD.GetDataTable(strWidgetSQL);

                                if(dtWidgetData!=null)
                                    if (dtWidgetData.Columns.Count > 0)
                                    {
                                        foreach (DataColumn dc in dtWidgetData.Columns)
                                        {
                                            UpdateHashTableWithColumn(ref htColumns, dc.ColumnName, dc.ColumnName);
                                        }
                                    }
                            }
                        break;
                    case "report":
                        sql = "select * from sy_report where af_row_id = '" + strSource + "'";
                        dt = HDD.GetDataTable(sql);
                        if (dt != null)
                            if (dt.Rows.Count > 0)
                            {
                                DataRow drReport = dt.Rows[0];
                                #region QueryBasedReport
                                if (drReport["rpt_base_object"].ToString().ToLower() == "true" || drReport["rpt_base_object"].ToString().ToLower() == "sql")
                                {
                                    string strReportAtt = "select * from sy_report_att where rpt_id = '" + strSource + "' order by attrib_sequence";
                                    DataTable dtReportAtt = HDD.GetDataTable(strReportAtt);
                                    if (dtReportAtt != null)
                                        if (dtReportAtt.Rows.Count > 0)
                                        {
                                            string strObjectID = dtReportAtt.Rows[0]["object_id"].ToString();
                                            if (strObjectID.Trim() != "")
                                            {
                                                string strsql = "select * from sy_report_sql where report_base_id = '" + strObjectID + "'";
                                                DataTable dtSQL = HDD.GetDataTable(strsql);
                                                if (dtSQL != null)
                                                    if (dtSQL.Rows.Count > 0)
                                                    {
                                                        //decode added by Sampath on 27-Apr-2012
                                                        //CommonFunctions.decodeData(dt);
                                                        strWidgetSQL = dtSQL.Rows[0]["report_base_sql"].ToString();
                                                        Hashtable hsParam = new Hashtable();
                                                        BuildParameters BP = new BuildParameters();
                                                        //hsParam = BP.updateParameters(strWidgetSQL, dtSQL.Rows[0]["report_base_param"].ToString(), frmObj, "");//dr["af_row_id"].ToString()
                                                        BP.GetParametersInHashTable(strWidgetSQL,dtSQL.Rows[0]["report_base_param"].ToString(),ref hsParam);
                                                        strWidgetSQL = BP.makeSQL(hsParam, strWidgetSQL);
                                                        //dtWidgetData = HDD.GetDataTable(strWidgetSQL);
                                                        //Hashtable htcaptions = new Hashtable();
                                                        HashColumnNames(ref htColumns, dtReportAtt);
                                                        //ReplaceColumnCaptions(htcaptions, ref dtWidgetData);
                                                        //RemoveColumns(htcaptions, ref dtWidgetData);
                                                    }
                                            }
                                        }


                                }
                                #endregion
                                #region ObjectBasedReport
                                else if (drReport["rpt_base_object"].ToString().ToLower() == "false" || drReport["rpt_base_object"].ToString().ToLower() == "object")
                                {

                                    sql = "select * from sy_report_att where rpt_id = '" + drReport["af_row_id"].ToString() + "' order by attrib_sequence";
                                    DataTable dtReportAtt = HDD.GetDataTable(sql);
                                    if (dtReportAtt != null)
                                    {
                                        if (dtReportAtt.Rows.Count > 0)
                                        {
                                            string object_id = dtReportAtt.Rows[0]["object_id"].ToString();
                                            string tablename = HDD.GetColumnValue("select object_table from sy_obj where object_id = '" + object_id + "'");

                                            DataTable dtPgCtr = HDD.GetDataTable("select * from sy_pg_ctr where page_id = (select af_row_id from sy_pg where object_id = '" + object_id + "')");
                                            DataTable dtBind = GetBindFields(dtPgCtr);

                                            if (drReport["rpt_base_object"].ToString().ToLower() == "false") // Old Maxblox Report
                                            {
                                                //string strQuery = "";
                                                //string strAttribID = "";
                                                foreach (DataRow dr1 in dtReportAtt.Rows)
                                                {
                                                    UpdateHashTableWithColumn(ref htColumns, dr1["attrib_id"].ToString(), dr1["caption"].ToString());
                                                }

                                            }
                                            else if (drReport["rpt_base_object"].ToString().ToLower() == "object") // New Maxblox Report
                                            {
                                                string strObjAtt = "select * From sy_obj_att where object_id = (select af_row_id from sy_obj where object_id = '" + object_id + "')";
                                                DataTable dtObjAtt = HDD.GetDataTable(strObjAtt);
                                                string strQuery = "select ";

                                                foreach (DataRow dratt in dtReportAtt.Rows)
                                                {

                                                    string strattibID = "";
                                                    string caption = "";
                                                    DataRow[] drObj = dtObjAtt.Select("af_row_id = '" + dratt["attrib_id"].ToString() + "'");
                                                    if (drObj.Length > 0)
                                                        strattibID = drObj[0]["attrib_id"].ToString();

                                                    if (dratt["caption"].ToString() != "")
                                                        caption = dratt["caption"].ToString();
                                                    else
                                                    {
                                                        caption = strattibID;
                                                        if (drObj.Length > 0)
                                                            caption = drObj[0]["attrib_name"].ToString();
                                                    }

                                                    //UpdateHashTableWithColumn(ref htColumns, strattibID, caption);
                                                    UpdateHashTableWithColumn(ref htColumns, caption, caption);

                                                }
                                            }
                                        }
                                    }
                                }
                                #endregion
                            }
                        break;
                    default:
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetWidgetSQL : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    private void UpdateHashTableWithColumn(ref Hashtable htColumns, string columnname,string caption)
    {
        try
        {
            if (!htColumns.ContainsKey(columnname))
                htColumns.Add(columnname, caption);
        }
        catch
        {
        }
    }

    private DataTable GetWidgetOrdinates(string strWidgetRowID)
    {
        DataTable dt = new DataTable();
        HDDatabase HDD = new HDDatabase();
        try
        {
            dt = HDD.GetDataTable("select * from sy_widget_ordinates where widget = '" + strWidgetRowID + "'");
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Dashboards : GetWidgetOrdinates : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return dt;
    }

    private void GetXYOrdinatesInArray(ref ArrayList arrXAxis, ref ArrayList arrYAxis,DataTable dtOrdinates,bool bFieldAndCaptionSame,DataTable dtWidgetData)
    {
        try
        {
            if(dtOrdinates!=null)
                if (dtOrdinates.Rows.Count > 0)
                {
                    //if (bFieldAndCaptionSame)
                    //{
                        DataRow[] drr = dtOrdinates.Select("axis_type = 'X'");
                        if (drr.Length > 0)
                        {
                            for (int i = 0; i < drr.Length; i++)
                            {
                                arrXAxis.Add(drr[i]["axis_column"].ToString());
                            }
                            drr = dtOrdinates.Select("axis_type = 'Y'");
                            if (drr.Length > 0)
                                for (int j = 0; j < drr.Length; j++)
                                {
                                    arrYAxis.Add(drr[j]["axis_column"].ToString());
                                }
                        }
                    //}
                    //else
                    //{

                    //}
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Dashboards : GetXYOrdinatesInArray :"+ ex.Message);
        }


    }


    #region Paramters
    //private Hashtable getParameters(string sChar, ref Hashtable hsParam, string sSql)
    //{
    //    try
    //    {
    //        int iPos = 0;
    //        while (iPos < sSql.Length & iPos != -1)
    //        {
    //            string sParam = "";
    //            iPos = sSql.IndexOf(sChar, iPos);
    //            if (iPos != -1)
    //            {
    //                int iEndPos = sSql.IndexOf(sChar, iPos + 1);
    //                if (iEndPos == -1)
    //                    iEndPos = sSql.Length - iPos;
    //                else
    //                    iEndPos = iEndPos - (iPos - 1);
    //                sParam = sSql.Substring(iPos, iEndPos);
    //                sParam = sParam.TrimEnd('\'');
    //                if (!hsParam.Contains(sParam))
    //                {
    //                    if (sChar == "$")
    //                        hsParam.Add(sParam, "'0'");
    //                    else if (sChar == "#")
    //                        hsParam.Add(sParam, "'" + DateTime.Now.ToShortDateString() + "'");
    //                }
    //                iPos = iPos + iEndPos;
    //            }
    //        }
    //    }
    //    catch (Exception Ex)
    //    {
    //        LogWriter.WriteLog("BuildParameters: getParameters : Error : " + Ex.Message);
    //    }
    //    return hsParam;
    //}

    //private void ReplaceParamtersWithEmptyValues(string sqlQry, string sqlParam, Control ctrlPage, string widgetAfRowId)
    //{
    //    try
    //    {
    //        Hashtable hsParam = new Hashtable();

    //        if (sqlParam.Trim() == "")
    //        {
    //            getParameters("$", ref hsParam, sqlQry);
    //            getParameters("#", ref hsParam, sqlQry);
    //        }
    //        else
    //        {
    //            if (sqlParam.Trim().ToLower().StartsWith("parameters"))
    //                sqlParam = sqlParam.Substring("parameters".Length + 1).Trim();

    //            foreach (string str1 in sqlParam.Split(','))
    //            {
    //                if (str1.Trim() == "") continue;
    //                if (str1.Trim() == "") continue;
    //                if (str1.IndexOf("=") == -1)
    //                    hsParam.Add(str1.Trim(), getDefaultValue(str1.Substring(str1.IndexOf("]") + 1).Trim()));
    //                else
    //                    hsParam.Add(str1.Substring(0, str1.IndexOf("=")).Trim(), str1.Substring(str1.IndexOf("=") + 1).Trim());
    //            }
    //        }
    //    }
    //    catch
    //    {
    //    }

    //}
    //private string getDefaultValue(string object_field_id)
    //{
    //    string retValue = "''";
    //    try
    //    {
    //        string object_table = object_field_id.Replace("[", "").Substring(0, object_field_id.Replace("[", "").IndexOf("."));
    //        string field_id = object_field_id.Substring(object_field_id.IndexOf(".") + 1).Replace("]", "");

    //        HDDatabase hdd = new HDDatabase();
    //        DataTable dt = hdd.GetDataTable("select control_attrib_type from sy_pg_ctr where control_id='" + field_id + "' and page_id=(select af_row_id from sy_pg where page_table_name='" + object_table + "')");
    //        if (dt.Rows.Count > 0)
    //        {
    //            if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "TX")
    //                retValue = "''";
    //            else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DA" || dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "DT")
    //                retValue = "'" + DateTime.Now.ToShortDateString() + "'";
    //            else if (dt.Rows[0]["control_attrib_type"].ToString().ToUpper() == "BO")
    //                retValue = "'false'";
    //            else
    //                retValue = "0";
    //        }
    //        dt = null;
    //        hdd = null;
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("BuildParameters: getDefaultValue: Error : " + ex.Message);
    //    }
    //    return retValue;
    //}
    #endregion


    private void SeriesBindCharts()
    {
        try
        {
            // Modified by 'Imran Gani' on 01-Nov-2012,
            SeriesBindingCharts.Add("area2d");
            SeriesBindingCharts.Add("bar2d");
            SeriesBindingCharts.Add("column2d");
            SeriesBindingCharts.Add("line2d");
            SeriesBindingCharts.Add("spline2d");
            SeriesBindingCharts.Add("stepline2d");
            SeriesBindingCharts.Add("area3d");
            SeriesBindingCharts.Add("bar3d");
            SeriesBindingCharts.Add("column3d");
            SeriesBindingCharts.Add("line3d");
            SeriesBindingCharts.Add("spline3d"); 
            SeriesBindingCharts.Add("stepline3d");
        }
        catch
        {
        }
    }

    

    #region unwanted
    //public string GetWidgetQuery(string strSource, string strSourceType, ref Hashtable htColumns)
    //{
    //    HDDatabase HDD = new HDDatabase();
    //    string strWidgetSQL = "";
    //    try
    //    {
    //        if (strSource.Trim() != "")
    //            if (strSourceType.Trim() != "")
    //            {
    //                string sql = "";
    //                DataTable dt = new DataTable();
    //                DataSet dsPageControls = new DataSet();

    //                switch (strSourceType.ToLower())
    //                {
    //                    case "query":
    //                        sql = "select * from sy_report_sql where af_row_id = '" + strSource + "'";
    //                        dt = HDD.GetDataTable(sql);
    //                        if (dt != null)
    //                        {
    //                            if (dt.Rows.Count > 0)
    //                            {
    //                                strWidgetSQL = dt.Rows[0]["report_base_sql"].ToString();
    //                                //DataTable dtOutput = HDD.GetDataTable(strWidgetSQL);
    //                            }
    //                        }
    //                        break;
    //                    case "report":
    //                        sql = "select * from sy_report where af_row_id = '" + strSource + "'";
    //                        dt = HDD.GetDataTable(sql);
    //                        if (dt != null)
    //                            if (dt.Rows.Count > 0)
    //                            {
    //                                DataRow drReport = dt.Rows[0];
    //                                #region QueryBasedReport
    //                                if (drReport["rpt_base_object"].ToString().ToLower() == "true" || drReport["rpt_base_object"].ToString().ToLower() == "sql")
    //                                {
    //                                    string strReportAtt = "select * from sy_report_att where rpt_id = '" + strSource + "' order by attrib_sequence";
    //                                    DataTable dtReportAtt = HDD.GetDataTable(strReportAtt);
    //                                    if (dtReportAtt != null)
    //                                        if (dtReportAtt.Rows.Count > 0)
    //                                        {
    //                                            string strObjectID = dtReportAtt.Rows[0]["object_id"].ToString();
    //                                            if (strObjectID.Trim() != "")
    //                                            {
    //                                                string strsql = "select * from sy_report_sql where report_base_id = '" + strObjectID + "'";
    //                                                DataTable dtSQL = HDD.GetDataTable(strsql);
    //                                                if (dtSQL != null)
    //                                                    if (dtSQL.Rows.Count > 0)
    //                                                    {
    //                                                        strWidgetSQL = dtSQL.Rows[0]["report_base_sql"].ToString();
    //                                                        Hashtable htcaptions = new Hashtable();
    //                                                        HashColumnNames(ref htcaptions, dtReportAtt);
    //                                                        ReplaceColumnCaptions(htcaptions, ref dtWidgetData);
    //                                                        //RemoveColumns(htcaptions, ref dtWidgetData);
    //                                                    }
    //                                            }
    //                                        }
    //                                }
    //                                #endregion
    //                                #region ObjectBasedReport
    //                                else if (drReport["rpt_base_object"].ToString().ToLower() == "false" || drReport["rpt_base_object"].ToString().ToLower() == "object")
    //                                {

    //                                    sql = "select * from sy_report_att where rpt_id = '" + drReport["af_row_id"].ToString() + "' order by attrib_sequence";
    //                                    DataTable dtReportAtt = HDD.GetDataTable(sql);
    //                                    if (dtReportAtt != null)
    //                                    {
    //                                        if (dtReportAtt.Rows.Count > 0)
    //                                        {
    //                                            string object_id = dtReportAtt.Rows[0]["object_id"].ToString();
    //                                            string tablename = HDD.GetColumnValue("select object_table from sy_obj where object_id = '" + object_id + "'");

    //                                            DataTable dtPgCtr = HDD.GetDataTable("select * from sy_pg_ctr where page_id = (select af_row_id from sy_pg where object_id = '" + object_id + "')");
    //                                            DataTable dtBind = GetBindFields(dtPgCtr);

    //                                            if (drReport["rpt_base_object"].ToString().ToLower() == "false") // Old Maxblox Report
    //                                            {
    //                                                string strQuery = "select ";
    //                                                string strAttribID = "";
    //                                                foreach (DataRow dr1 in dtReportAtt.Rows)
    //                                                {
    //                                                    strAttribID += "'" + dr1["attrib_id"].ToString() + "',";
    //                                                    DataRow drbnd = null;
    //                                                    DataRow[] drctr = dtPgCtr.Select("control_attrib_id= '" + dr1["attrib_id"].ToString() + "'");
    //                                                    if (drctr.Length > 0)
    //                                                    {
    //                                                        if (drctr[0]["control_bind_id"].ToString().Trim() != "")
    //                                                        {
    //                                                            drbnd = dtBind.Select("af_row_id='" + drctr[0]["control_bind_id"].ToString() + "'")[0];
    //                                                        }
    //                                                    }

    //                                                    if (drbnd != null)
    //                                                    {
    //                                                        string innersql = "(select top 1 " + drbnd["bind_text"].ToString() + " from " + drbnd["bind_table"].ToString() + " where " + drbnd["bind_value"].ToString() + "= [" + tablename + "].[" + dr1["attrib_id"].ToString() + "])";
    //                                                        strQuery += innersql + " as [" + dr1["caption"].ToString() + "],";
    //                                                    }
    //                                                    else
    //                                                    {
    //                                                        strQuery += dr1["attrib_id"].ToString() + " as [" + dr1["caption"].ToString() + "],";
    //                                                    }
    //                                                }

    //                                                strQuery = strQuery.TrimEnd(',');
    //                                                strAttribID = strAttribID.TrimEnd(',');
    //                                                strQuery += " from " + tablename + " where 1=1 ";


    //                                                strWidgetSQL = strQuery;
    //                                                bool status = dr["ignore_owner_security"].ToString() != "" ? Convert.ToBoolean(dr["ignore_owner_security"].ToString()) : false;
    //                                                if (!status)
    //                                                {
    //                                                    SecurityFilter SF = new SecurityFilter();
    //                                                    strWidgetSQL = SF.applysecurity(strWidgetSQL);
    //                                                }
    //                                                else
    //                                                {
    //                                                    strWidgetSQL = applyafadminsecurity(strWidgetSQL);
    //                                                }

    //                                                dtWidgetData = HDD.GetDataTable(strWidgetSQL);

    //                                            }
    //                                            else if (drReport["rpt_base_object"].ToString().ToLower() == "object") // New Maxblox Report
    //                                            {
    //                                                string strObjAtt = "select * From sy_obj_att where object_id = (select af_row_id from sy_obj where object_id = '" + object_id + "')";
    //                                                DataTable dtObjAtt = HDD.GetDataTable(strObjAtt);
    //                                                string strQuery = "select ";

    //                                                foreach (DataRow dratt in dtReportAtt.Rows)
    //                                                {

    //                                                    string strattibID = "";
    //                                                    string caption = "";
    //                                                    DataRow[] drObj = dtObjAtt.Select("af_row_id = '" + dratt["attrib_id"].ToString() + "'");
    //                                                    if (drObj.Length > 0)
    //                                                        strattibID = drObj[0]["attrib_id"].ToString();

    //                                                    if (dratt["caption"].ToString() != "")
    //                                                        caption = dratt["caption"].ToString();
    //                                                    else
    //                                                    {
    //                                                        caption = strattibID;
    //                                                        if (drObj.Length > 0)
    //                                                            caption = drObj[0]["attrib_name"].ToString();
    //                                                    }


    //                                                    DataRow drbnd = null;
    //                                                    DataRow[] drctr = dtPgCtr.Select("control_attrib_id= '" + strattibID + "'");
    //                                                    if (drctr.Length > 0)
    //                                                    {
    //                                                        if (drctr[0]["control_bind_id"].ToString().Trim() != "")
    //                                                        {
    //                                                            drbnd = dtBind.Select("af_row_id='" + drctr[0]["control_bind_id"].ToString() + "'")[0];
    //                                                        }
    //                                                    }

    //                                                    if (drbnd != null)
    //                                                    {
    //                                                        string innersql = "(select top 1 " + drbnd["bind_text"].ToString() + " from " + drbnd["bind_table"].ToString() + " where " + drbnd["bind_value"].ToString() + "= [" + tablename + "].[" + strattibID + "])";
    //                                                        strQuery += innersql + " as [" + caption + "],";
    //                                                    }
    //                                                    else
    //                                                    {
    //                                                        strQuery += strattibID + " as [" + caption + "],";
    //                                                    }

    //                                                }

    //                                                strQuery = strQuery.TrimEnd(',');
    //                                                strQuery += " from " + tablename + " where 1=1 ";
    //                                                strWidgetSQL = strQuery;
    //                                                bool status = dr["ignore_owner_security"].ToString() != "" ? Convert.ToBoolean(dr["ignore_owner_security"].ToString()) : false;
    //                                                if (!status)
    //                                                {
    //                                                    SecurityFilter SF = new SecurityFilter();
    //                                                    strWidgetSQL = SF.applysecurity(strWidgetSQL);
    //                                                }
    //                                                else
    //                                                {
    //                                                    strWidgetSQL = applyafadminsecurity(strWidgetSQL);
    //                                                }
    //                                                dtWidgetData = HDD.GetDataTable(strWidgetSQL);
    //                                            }
    //                                        }
    //                                    }
    //                                }
    //                                #endregion
    //                            }
    //                        break;
    //                    default:
    //                        break;
    //                }
    //            }
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : GetWidgetSQL : " + ex.Message);
    //    }
    //    finally
    //    {
    //        HDD = null;
    //    }


    //}
    #endregion
    #endregion

    #region Object based report source filter needs.
    // Added by Imran Gani on 04-Dec-2012, for Source Filter.
    /// <summary>
    /// To get the where condition for the object.
    /// </summary>
    /// <param name="sTableName">Table Name of Object</param>
    /// <param name="drReport">Report data row</param>
    /// <returns>Where condition for object.</returns>
    private string getWhereCondForObj(string sTableName, DataRow drReport, DataTable dtPgCtr, HDDatabase HDD) 
    {
        string sWhere = string.Empty, temp;
        DataSet dsRptSrcFlt = new DataSet();
        DataTable dtSrcfil = new DataTable();
        DataTable dtReport_Source_filter = new DataTable();
        try
        {
            dsRptSrcFlt.Tables.Add(dtPgCtr.Copy());
            dsRptSrcFlt.Tables.Add(HDD.GetDataTable("select * from sy_acr_mem where acr_id='3123fa00e7b08e2B';", "Expression").Copy());

            dtReport_Source_filter = HDD.GetDataTable("select * from sy_report_source_filter where rpt_id = '" + drReport["af_row_id"] + "';");
            if (dtReport_Source_filter != null && dtReport_Source_filter.Rows.Count > 0)
            {
                dtSrcfil = JsonFunctions.JsonFunctions.JsonToDataTable("{\"a\":[ " + getSourceFilterInputData(dtReport_Source_filter, dsRptSrcFlt, HDD) + " ]}");
                if (dtSrcfil != null && dtSrcfil.Rows.Count > 0)
                {
                    if (dtSrcfil.Rows.Count > 1)
                    {
                        sWhere = drReport["source_filter_grouping"].ToString();
                        sWhere = sWhere.ToLower().Replace("and", " and ").Replace("or", " or ");
                        for (int j = 1; j <= dtSrcfil.Rows.Count; j++)
                        {
                            sWhere = sWhere.Replace(Convert.ToString(j) + " ", "$" + Convert.ToString(j)).Replace(" " + Convert.ToString(j), "$" + Convert.ToString(j));
                        }
                        int i = 0;
                        foreach (DataRow dr in dtSrcfil.Rows)
                        {
                            i++;
                            temp = getCondition(dr["cndid"].ToString(), dr["fldid"].ToString(), dr["val"].ToString(), sTableName, dsRptSrcFlt);
                            sWhere = sWhere.Replace("$" + Convert.ToString(i), temp);
                        }
                    }
                    else
                    {
                        sWhere = getCondition(dtSrcfil.Rows[0]["cndid"].ToString(), dtSrcfil.Rows[0]["fldid"].ToString(), dtSrcfil.Rows[0]["val"].ToString(), sTableName, dsRptSrcFlt);
                    }
                }
            }
            else
                sWhere = "1=1";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getWhereCondForObj : " + ex.Message);
        }
        finally
        {
            temp = string.Empty; dtSrcfil.Dispose();
        }
        return " where " + sWhere;
    }

    /// <summary>
    /// To get the source filter display grid details.
    /// </summary>
    /// <param name="dt">DataTable of source filter.</param>
    /// <param name="dsRptSrcFlt">DataSet for Page control and Expression</param>
    /// <returns>Json String</returns>
    private string getSourceFilterInputData(DataTable dt, DataSet dsRptSrcFlt, HDDatabase hdd) 
    {
        BindControl bc = new BindControl();
        StringBuilder sbHidden = new StringBuilder();
        GenerateGrid gg = new GenerateGrid();
        ArrayList alValueList = new ArrayList();
        string sFld = string.Empty, sVal;
        try
        {
            foreach (DataRow dr in dt.Select("", "sequence"))
            {
                alValueList.Clear();
                sVal = dr["field_value"].ToString();
                if (sVal.Contains("|") && sVal.EndsWith("|"))
                {
                    sVal = sVal.TrimEnd('|');
                    alValueList.AddRange(sVal.Split('|'));
                }
                DataRow[] drPgCtr = dsRptSrcFlt.Tables[0].Select("af_row_id='" + dr["field"].ToString() + "'");
                if (drPgCtr.Length > 0)
                {
                    if (sVal != "" && drPgCtr[0]["control_bind_id"].ToString() != "")
                    {
                        string sBindSql = bc.GetBindSql_forValue(drPgCtr[0]["control_bind_id"].ToString());
                        if (alValueList.Count > 0)
                        {
                            sVal = "";
                            foreach (string sValue in alValueList)
                            {
                                sVal += hdd.GetColumnValue(sBindSql + "'" + sValue + "'") + ", ";
                            }
                            sVal = sVal.Trim();
                        }
                        else
                            sVal = hdd.GetColumnValue(sBindSql + "'" + sVal + "'");
                    }
                    if (drPgCtr[0]["control_attrib_type"].ToString() == "DA" || drPgCtr[0]["control_attrib_type"].ToString() == "DT")
                        sVal = gg.manageDateTimeValues(drPgCtr[0]["control_attrib_type"].ToString().ToLower(), sVal);
                    if (alValueList.Count > 0 && drPgCtr[0]["control_bind_id"].ToString() == "")
                    {
                        sVal = "";
                        foreach (string sValue in alValueList)
                        {
                            sVal += sValue + ", ";
                        }
                        sVal = sVal.Trim();
                    }
                    DataRow drCond = dsRptSrcFlt.Tables[1].Select("mem_id='" + dr["condition"].ToString() + "'")[0];
                    sbHidden.Append("{\"fld\":\"" + drPgCtr[0]["control_name"].ToString() + "\",\"fldid\":\"" + dr["field"].ToString() + "\",\"cnd\":\"" + drCond["mem_name"].ToString() + "\",\"cndid\":\"" + dr["condition"].ToString() + "\",\"txt\":\"" + sVal + "\",\"val\":\"" + dr["field_value"].ToString() + "\"},");
                }
                else
                    return "";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getSourceFilterInputData : " + ex.Message);
        }
        finally
        {
            bc = null; gg = null; sFld = string.Empty; sVal = string.Empty; alValueList = null;
        }
        return sbHidden.ToString().TrimEnd(',');
    }

    /// <summary>
    /// To get the condition.
    /// </summary>
    /// <param name="sCondId">Condition</param>
    /// <param name="sFldId">Field</param>
    /// <param name="sVal">Value</param>
    /// <param name="sTableName">Table</param>
    /// <returns>Condition</returns>
    private string getCondition(string sCondId, string sFldId, string sVal, string sTableName, DataSet dsRptSrcFlt) 
    {
        string temp = "";
        ArrayList alValueList = new ArrayList();
        try
        {
            if (sVal.Contains("|") && sVal.EndsWith("|"))
            {
                sVal = sVal.TrimEnd('|');
                alValueList.AddRange(sVal.Split('|'));
            }
            DataRow drCond = dsRptSrcFlt.Tables[1].Select("mem_id='" + sCondId + "'")[0];
            DataRow drColId = dsRptSrcFlt.Tables[0].Select("af_row_id='" + sFldId + "'")[0];
            switch (sCondId)
            {
                case "NULL":
                case "NNULL":
                    temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString();
                    break;
                case "NEQ":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sValue.Replace("'", "''") + "' and ";
                        }
                        temp = temp.Substring(0, temp.Length - 4);
                        temp += "or [" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] is null";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "' or [" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] is null";
                    break;
                case "IN":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "'" + sValue.Replace("'", "''") + "',";
                        }
                        temp = temp.TrimEnd(',');
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " (" + temp + ")";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
                case "NIN":
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "'" + sValue.Replace("'", "''") + "',";
                        }
                        temp = temp.TrimEnd(',');
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " (" + temp + ")";
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
                default:
                    if (alValueList.Count > 0)
                    {
                        foreach (string sValue in alValueList)
                        {
                            temp += "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sValue.Replace("'", "''") + "' or ";
                        }
                        temp = temp.Substring(0, temp.Length - 4);
                    }
                    else
                        temp = "[" + sTableName + "].[" + drColId["control_id"].ToString().Replace("'", "''") + "] " + drCond["mem_value1"].ToString() + " '" + sVal.Replace("'", "''") + "'";
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : getCondition : " + ex.Message);
        }
        finally
        {
            alValueList = null;
        }
        return temp;
    }
    #endregion

    #region Function Added by 'Imran Gani' on 06-Mar-2014, for handling datatype for grid datatable.
    /// <summary>
    /// To handle data type of a datatable for locale format.
    /// </summary>
    /// <param name="dtWidgetData">DataTable to be handle locale.</param>
    /// <param name="drWidget">DataRow of widget for details.</param>
    private void HandleDataType4GridTable(DataTable dtWidgetData, DataRow drWidget)
    {
        HDDatabase HDD = new HDDatabase();
        Localization loc = new Localization();
        try
        {
            if (dtWidgetData!=null && drWidget != null)
            {
                string strSourceType = drWidget["source_type"].ToString();
                string strSource = drWidget["source"].ToString();
                string sql = "";
                DataTable dt = new DataTable();
                DataTable dtWidgetData_Clone = new DataTable();
                dtWidgetData_Clone = dtWidgetData.Clone();
                switch (strSourceType.ToLower())
                {
                    case "query":
                        foreach (DataColumn dcSQL in dtWidgetData_Clone.Columns)
                        {
                            string sColName = dcSQL.ColumnName;
                            string sColDataType = dcSQL.DataType.ToString();
                            switch (sColDataType.ToLower())
                            {
                                case "system.double":
                                case "system.decimal":
                                    dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dc", sColName);
                                    break;
                                case "system.int32":
                                    dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "nu", sColName);
                                    break;
                                case "system.datetime":
                                    dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dt", sColName);
                                    break;
                            }
                        }
                        break;
                    case "report":
                        sql = "select * from sy_report where af_row_id = '" + strSource + "'";
                        dt = HDD.GetDataTable(sql);
                        if (dt != null)
                            if (dt.Rows.Count > 0)
                            {
                                DataRow drReport = dt.Rows[0];
                                #region QueryBasedReport
                                if (drReport["rpt_base_object"].ToString().ToLower() == "true" || drReport["rpt_base_object"].ToString().ToLower() == "sql")
                                {
                                    foreach (DataColumn dcSQL in dtWidgetData_Clone.Columns)
                                    {
                                        string sColName = dcSQL.ColumnName;
                                        string sColDataType = dcSQL.DataType.ToString();
                                        switch (sColDataType.ToLower())
                                        {
                                            case "system.double":
                                            case "system.decimal":
                                                dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dc", sColName);
                                                break;
                                            case "system.int32":
                                                dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "nu", sColName);
                                                break;
                                            case "system.datetime":
                                                dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dt", sColName);
                                                break;
                                        }
                                    }
                                }
                                #endregion
                                #region ObjectBasedReport
                                else if (drReport["rpt_base_object"].ToString().ToLower() == "false" || drReport["rpt_base_object"].ToString().ToLower() == "object")
                                {
                                    sql = "select * from sy_report_att where rpt_id = '" + drReport["af_row_id"].ToString() + "' order by attrib_sequence";
                                    DataTable dtReportAtt = HDD.GetDataTable(sql);
                                    if (dtReportAtt != null && dtReportAtt.Rows.Count > 0)
                                    {
                                        string object_id = dtReportAtt.Rows[0]["object_id"].ToString();
                                        DataTable dtObjAtt = HDD.GetDataTable("select * from sy_obj_att where object_id = (select af_row_id from sy_obj where object_id = '" + object_id + "')");
                                        DataRow[] dr = null;
                                        foreach (DataColumn dcObj in dtWidgetData_Clone.Columns)
                                        {
                                            string sColName = dcObj.ColumnName;
                                            dr = dtReportAtt.Select("caption = '" + sColName + "'");
                                            if (dr == null || dr.Length == 0)
                                                dr = dtObjAtt.Select("attrib_id = '" + sColName + "'");
                                            else
                                                dr = dtObjAtt.Select("af_row_id = '" + dr[0]["attrib_id"].ToString() + "'");
                                            if (dr == null || dr.Length == 0)
                                            {
                                                string sColDataType = dcObj.DataType.ToString();
                                                switch (sColDataType.ToLower())
                                                {
                                                    case "system.double":
                                                    case "system.decimal":
                                                        dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dc", sColName);
                                                        break;
                                                    case "system.int32":
                                                        dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "nu", sColName);
                                                        break;
                                                    case "system.datetime":
                                                        dtWidgetData = loc.getLocalizedColumns(dtWidgetData, "dt", sColName);
                                                        break;
                                                }
                                            }
                                            else
                                                dtWidgetData = loc.getLocalizedColumns(dtWidgetData, dr[0]["attrib_data_type"].ToString(), sColName);
                                        }
                                    }
                                }
                                #endregion
                            }
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Dashboards : HandleDataType4GridTable :" + ex.Message);
        }
    }
    #endregion

    private void getWidthHeight4Chart(ref int width, ref int height, DataRow drWidget)
    {
        try
        {
            width = 400;
            height = 300;
            int screenWidth = 1600;
            //screenWidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width - 70; // Will give server screen width size
            if (dtWidgetProperty != null && dtWidgetProperty.Rows.Count > 0)
            {
                DataRow[] dr = dtWidgetProperty.Select("widget = '" + drWidget["af_row_id"].ToString() + "'");
                if (dr.Length > 0)
                {
                    if (dr[0]["fullview"].ToString().ToLower() == "true")
                    {
                        width = screenWidth;
                        height = Convert.ToInt32(width * 0.45);
                    }
                    else if (dr[0]["widget_size"].ToString().ToLower() == "small")
                    {
                        width = ((screenWidth / dashboardColumns) / 2) - 5;
                        height = Convert.ToInt32(width * 0.65);
                    }
                    else
                    {
                        width = screenWidth / dashboardColumns;
                        height = Convert.ToInt32(width * 0.65);
                    }
                }
                else
                {
                    width = screenWidth / dashboardColumns;
                    height = Convert.ToInt32(width * 0.65);
                }
            }
            else
            {
                width = screenWidth / dashboardColumns;
                height = Convert.ToInt32(width * 0.65);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Dashboards : getWidthHeight4Chart :" + ex.Message);
        }
    }

    // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard small widget
    private HtmlTable getSmallwidget(string strDBafrowid, ref int cnt, ArrayList list, DataTable dtWdgSettings, HtmlForm frmObj)
    {
        HtmlTable ht_small = new HtmlTable();
        try
        {
            HtmlTableRow htr_small = new HtmlTableRow();
            HtmlTableCell htc_small = new HtmlTableCell();

            GenerateWidgets(strDBafrowid, ref htc_small, true, frmObj, true);
            if (list.Count > cnt)
            {
                strDBafrowid = list[cnt].ToString();
                DataRow[] dr = dtWdgSettings.Select("widget = '" + strDBafrowid + "'");
                if (dr.Length > 0)
                {
                    if (dr[0]["widget_size"].ToString().ToLower() == "small")
                    {
                        htr_small.Controls.Add(htc_small);
                        htc_small = new HtmlTableCell();
                        GenerateWidgets(strDBafrowid, ref htc_small, true, frmObj, true);
                        htr_small.Controls.Add(htc_small);
                        cnt += 2;
                    }
                    else
                    {
                        htc_small.ColSpan = 2;
                        htr_small.Controls.Add(htc_small);
                        cnt += 1;
                    }
                }
                else
                {
                    htc_small.ColSpan = 2;
                    htr_small.Controls.Add(htc_small);
                    cnt += 1;
                }
            }
            else
            {
                htc_small.ColSpan = 2;
                htr_small.Controls.Add(htc_small);
                cnt += 1;
            }
            ht_small.Controls.Add(htr_small);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Dashboards : getSmallwidget :" + ex.Message);
        }
        return ht_small;
    }

    // Added by 'Imran Gani' on 05-Sep-2014, for Dashboard Text widget
    private void createTextContent(DataRow drWidget, ref HtmlTableCell htc, HtmlForm frmObj)
    {
        try
        {
            Panel ObjTextChart = new Panel();
            ObjTextChart.ID = "wgt_" + drWidget["af_row_id"].ToString();
            ObjTextChart.BackColor = Color.White;
            ObjTextChart.ScrollBars = ScrollBars.Auto;
            ObjTextChart.BorderColor = Color.LightGray;
            ObjTextChart.BorderStyle = BorderStyle.Solid;
            ObjTextChart.BorderWidth = 1;
            //ObjTextChart.Controls.Add(new LiteralControl(drWidget["text_content"].ToString()));
            int width = 400;
            int height = 300;
            string strSQL = "", sTextContent = "";
            DataTable dtWidgetData = new DataTable();

            //XY Axis changes
            ArrayList arrXAxis = new ArrayList();
            ArrayList arrYAxis = new ArrayList();

            sTextContent = drWidget["text_content"].ToString();
            GetWidgetData(drWidget, ref strSQL, ref dtWidgetData, frmObj, ref arrXAxis, ref arrYAxis);
            if (dtWidgetData.Rows.Count > 0)
            {
                foreach (DataColumn dc in dtWidgetData.Columns)
                {
                    sTextContent = Regex.Replace(sTextContent, "\\$" + dc.ColumnName + "\\$", dtWidgetData.Rows[0][dc.ColumnName].ToString(), RegexOptions.IgnoreCase);
                    //if (sTextContent.ToLower().Contains("$" + dc.ColumnName.ToLower() + "$"))
                    //sTextContent = sTextContent.Replace("$" + dc.ColumnName + "$", dtWidgetData.Rows[0][dc.ColumnName].ToString());
                }
            }
            ObjTextChart.Controls.Add(new LiteralControl(sTextContent));
            getWidthHeight4Chart(ref width, ref height, drWidget);

            // Below width & height are added by 'Imran Gani' on 22-Jun-2012, to set the chart size.
            string sTempUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
            if (!sTempUrl.Contains("WidgetsView.aspx?"))
            {
                ObjTextChart.Width = Unit.Pixel(width);
                ObjTextChart.Height = Unit.Pixel(height);
            }
            else
            {
                height = Convert.ToInt32(width * 0.45);
                ObjTextChart.Width = Unit.Pixel(width);
                ObjTextChart.Height = Unit.Pixel(height);
            }
            htc.Controls.Add(ObjTextChart);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ApplyMSChartSettings :" + ex.Message);
        }
    }
         
}
